skip to Main Content

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


  1. 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:

    export default function ListItem({
      hasPrepend = false,
      prepend = { background: "bg-success", icon: { style:"fas", name: "fa-star" } },
      children,
    }) {
    

    Would become this:

    export default function ListItem({
      hasPrepend = false,
      prepend = { background = "bg-success", icon: { style = "fas", name = "fa-star" } },
      children,
    }) {
    

    But if you wanted to name the background property something more specific, like buttonBackground, that would be:

    export default function ListItem({
      hasPrepend = false,
      prepend = { background: btnBackground, ...},
      children,
    }) {
    
    Login or Signup to reply.
  2. You could save a file called defaultStyles.json,

    {
      "hasPrepend": false,
      "prepend": { "background": btnBackground},
      "name": "someName"
    }
    

    or something similar, import it into your component, and then use it like so

    import defaultStyles from './defaultStyles.json';
    ...
            <Icon style={defaultStyles} name={defaultStyles.name} />
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search