Default props
- React course
- Beginner
- Lesson 20/84
- 4 min
Learn to use a default value when a prop is missing.
Default props
Sometimes a prop might not arrive. To keep the component safe you give a default value. It's written inside destructuring with =: ({ '{ name = "Guest" }' }).
This is JavaScript's default parameter feature. If the name prop is missing or undefined, "Guest" is used automatically.
Default values make the component flexible: they define a fallback behaviour for non-required props.
Default props benefits
Default props make the component robust. For example, an Avatar called without a name prop shows "Guest" by default.
This approach is also common in API design: setting defaults for optional props reduces the caller's burden.
The same syntax works for several props: ({ '{ name = "Guest", role = "User" }' }).
Practice Avatar with default name
Complete the skeleton. Write a component called Avatar that takes ({ '{ name = "Misafir" }' }) as parameter and returns <p>{name}</p>. Don't forget to export.
Starter code
// Write the Avatar component hereSample solution
function Avatar({ name = "Misafir" }) {
return <p>{name}</p>;
}
export default Avatar;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is a default prop used?
- On a render error
- Whenever the prop arrives
- When the prop is missing Correct answer
- When state changes
Explanation: A default prop kicks in when the prop is missing.
2 Default value syntax
The default for name is ____.
The default for name is "Misafir".
Explanation: "Misafir" is a default value.
3 Match default props examples
| Term | Meaning |
|---|---|
name = "Guest" |
One default |
role = "User" |
Second default |
{ name } |
Required prop |
props |
Whole object |