Home > Software design >  Spreading React Props
Spreading React Props

Time:05-24

const RoundedIcon = ({
  name,
  size,
  color,
  backgroundColor,
}: RoundedIconProps) => {
  return (
    <Box
      height={size}
      width={size}
      justifyContent="center"
      alignItems="center"
      style={{ borderRadius: size / 2 }}
      {...{ backgroundColor }}
    />
  );
};

I understand how to use the spread operator and how you can easily spread the rest of any additional props to a React child, but can someone explain to me why this person is adding extra curly braces to an already destructered prop 'backgroundColor' of RoundedIcon component?

CodePudding user response:

In my opinion, it does not make sense. It may just be an artefact of this person doing:

{...{ backgroundColor, name, color }}

and then not needing name or color anymore to be spreaded in the props. So leaving

{...{ backgroundColor }}

Because it's exactly the same as:

backgroundColor={backgroundColor}

After writing this, I realized that it may be faster to type, and so you don't have a messy two times 'backgroundColor' in your code.

CodePudding user response:

In your case above spreading {...{ backgroundColor }} will pass backgroundColor in props to the child component. But if you want to rename the variable you have to spread it like below:

function ComponentA() {
  const backgroundColor = "red";

  return (
    <div>
      <p>Component A</p>
      <ComponentB {...{ helloWorld: backgroundColor }} />
    </div>
  );
}

function ComponentB(props) {
  console.log(props); // { helloWorld: "red" }

  return <div>Component B</div>;
}

CodePudding user response:

I doubt there is any reason why this {...{ backgroundColor }} is better than backgroundColor={backgroundColor}

  • Related