Trying to set the default value for some of my component properties. Doing a simple string or boolean works just fine, but I can’t find any examples showing something more complex. I’ve tried a few things to apply defaults to the prepend
property without success:
export default function ListItem({
hasPrepend = false,
prepend = { background: "bg-success", icon: { style:"fas", name: "fa-star" } },
children,
}) {
return(
<div>
{hasPrepend && <div className={`
${prepend.background}
`}
>
<Icon style={prepend.icon.style} name={prepend.icon.name} />
</div>
}
<div>
{children}
</div>
</div>
);
}
I’ve also tried
const defaultPrepend = {
background: "bg-success",
icon: {
style: "fas",
name: "fa-user",
size: "fa-lg",
}
};
export default function ListItem({
...
prepend = defaultPrepend,
...
}) {
Am I even close?
2
Answers
Using the
:
reassigns the variable to a different name. This is useful if you want to expose the prop as a name that makes more sense outside of the component, but within the component that name would cause naming conflicts. It’s a bit of a weird syntax, but you have to use the=
sign to set a default, despite it being part of an object.This:
Would become this:
But if you wanted to name the background property something more specific, like
buttonBackground
, that would be:You could save a file called
defaultStyles.json
,or something similar, import it into your component, and then use it like so