How to Set Default Props for Functional Components in React
In React, we use props
to pass down values from parent components to their children. When we create functional components, we need to consider that some of the values passed down as props
might not be there.
This is where we need to have the default props
. Today’s tutorial uses two approaches to demonstrate how we can set default props
for functional components in React.
React - Set Default props
for Functional Components
There are two approaches for setting default props
for functional components in React. Here, we will discuss and learn both methods and highlight which one is better to use.
Set Default Parameters in Function Definition
The first approach is to use the default parameters feature in JavaScript. Let’s look at an example below:
export default function App() {
return (
<div className="App">
<Child firstName="George" lastName="Smith" />
</div>
);
}
function Child({ firstName = "Irakli", lastName = "Tchigladze" }) {
return (
<div className="App">
<h1>{firstName + " " + lastName}</h1>
</div>
);
}
If the parent component passes down the firstName
and lastName
props
, like in the above example, values specified in the parent component will replace default values.
If these props
are not passed down, the child component will use values set as default parameters.
Now, try to delete the props
set on the <Child />
component. The child component requires these values to render a text on the page.
If we did not set the default parameters, not passing down necessary values will result in an error, like firstName is not defined
.
Setting default parameters helps us avoid this error. So instead, the <Child>
component will replace these variables with default parameters.
Use the defaultProps
Parameter to Set Default Parameters
Another way to set default values is via the defaultProps
property. Let’s rewrite the previous example using this method:
const Child = ({ firstName = "Irakli", lastName = "Tchigladze" }) => {
return (
<div className="App">
<h1>{firstName + " " + lastName}</h1>
</div>
);
};
Child.defaultProps = { firstName: "Irakli", lastName: "Tchigladze" };
In this case, we set the defaultProps
property equal to another object. The child component will default to this object when no props
are passed down from the parent component.
This syntax is relatively straightforward, although it requires a few additional lines of code.
However, the bigger problem is that according to Dan Abramov, one of the prominent people behind React, the functional component’s support for the defaultProps
property will be deprecated.
If you think you must care about the long-term stability of your project, it’s better to use default parameters rather than set default props using the defaultProps
property.
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn