Sometimes, we want to set default values for React component props.
In this article, we’ll look at how to set default values for React component props.
Set React Component Default Prop Values
We can add default props to make sure we always have some values set for our props.
To set default props, we use the defaultProps
property to set the default values of each prop.
For instance, we can write the following code to set default props for the Person
component that we have above:
import React from "react";
const persons = [
{ firstName: "Jane", lastName: "Smith" },
{ firstName: "Alex", lastName: "Jones" },
{ firstName: "May", lastName: "Wong" },
{}
];
const Person = ({ firstName, lastName }) => (
<div>
{firstName} {lastName}
</div>
);
Person.defaultProps = {
firstName: "No",
lastName: "Name"
};
export default function App() {
return (
<div>
{persons.map((p, i) => (
<Person {...p} key={i} />
))}
</div>
);
}
In the code above, we added:
Person.defaultProps = {
firstName: "No",
lastName: "Name"
};
to set the default values of the firstName
and lastName
props.
Then we’ll get the following displayed on the screen:
Jane Smith
Alex Jones
May Wong
No Name
Since we have an empty object in the persons
array as the last entry. Therefore, the default values are rendered in place of whatever is passed in.
Conclusion
We can add default props to make sure we always have some values set for our props.
To set default props, we use the defaultProps
property to set the default values of each prop.