Setting a Default Value to the props in React
In this tutorial, we are going to learn about how to set a default value to the props in React using defaultProps object.
Props
In react, props help us to pass the data from a parent component to the child component, but if we forgot to pass a prop value to child component react doesn’t render anything into the dom.
To solve this problem, we can set a default value to the prop using defaultProps
, so that react renders it whenever we don’t pass a prop value from the parent component.
Setting a Default value using defaultProps
To set a default value to the prop, we need to add properties
to the defaultProps
object.
import React from "react";
export default function Welcome(props){
return <h1>Welcome {props.name}</h1>
}
// setting default value to name prop
Welcome.defaultProps = {
name: "Boss"}
import React from "React";
import Welcome from "./Welcome";
export default function App() {
return (
<div>
<Welcome /> <p>My first react app</p>
</div>
);
}
In the above code, we are not passing a name
prop to the Welcome
component, so that react uses the default prop value we defined inside the Welcome
component.
In class-based components, we can use the defaultProps
as a static property to set the default values.
import React, {Component} from "react";
class Welcome extends Component {
static defaultProps = {
name: "king", };
render() {
return <h1>Welcome {this.props.name}</h1>;
}
}
export default Welcome;