React › Props & State
How would you give a prop a default value in case the parent does not pass one?
IntermediateAnswer
You can use default parameter syntax directly when destructuring props inside the function's parameter list, giving a fallback value that is used automatically whenever that specific prop is left out by the parent component.
function Button({ label = 'Click Me', color = 'blue' }) {
return <button style={{ backgroundColor: color }}>{label}</button>;
}
<Button /> // shows a blue button labeled Click Me
<Button label="Submit" /> // shows a blue button labeled SubmitReal-world example A shared Button component always shows a sensible default label and color even if a developer forgets to specify them, thanks to default values set directly in the component's props.