I’ve created a component that has default values of its props to be objects. Am I able to pass in a value for only 1 of the keys while leaving the others as default?
Example:
Let’s say this is the component:
export default function PageHeader({
heading = {
options: "",
customStyles: {},
text: ""
}
}) {
return (
<h1 className={heading.options} style={heading.customStyles}>
{heading.text}
</h1>
);
}
Assuming the only thing I want to change from the default prop object’s values is the text. Is there a way for me to do something like this:
<PageHeader heading = {...heading, text: 'New Text'} />
or
<PageHeader heading.text='New Text' />
Or would I have to pass in the entire heading prop object/not use an object and have each key be its own standalone prop?
2
Answers
If you are set on passing the object you can do it a few ways.
Consider this
Or you can use null-coalescing
and call like so, only specifying the properties you want to change from default
<PageHeader heading={{ text: "some other text" }} />
I’d recommend using flattened properties instead of a
header
object with properties. You can leveragedefaultProps
to achieve the result you want without manually merging props:Here’s a demo utilizing the above code: