When should I use "{ ...props }" instead of "props" in React?

Asked

Viewed 71 times

0

I’m done some testing and somewhere I saw they were using { ...props } in the component parameter. What’s the difference of using { ...props } of only props?

export default function Botao(props) { ... }
export default function Botao({ ...props }) { ... }
  • 2

    https://answall.com/q/111497/112052

  • 2

    It doesn’t make much sense to use Rest parameters when it comes to a function that will be used for React components, since they are not variable.

  • Did you mean Botao({...props}), right?

  • @Rafaeltavares that’s right, but my question has already been answered. Thank you

  • @Christianviana if the doubt has been resolved, accepts the answer as "Best answer".

1 answer

3


In the first example you receive the object - containing all the attributes passed.

e. g.

export default function Button(props) { 
  return <button style={{ backgroundColor: props.backgroundColor}>{props.label}</button>
}

<Button backgroundColor="red" label="Click here" />

In the second example you can use destructuring assignment to "destroy" the desired attributes and later we use the spread operator to assign the other attributes to props.

e. g.

export default function Button({ label, backgroundColor, ...props }) {
  return <button style={{ backgroundColor }} {...props}>{label}</button>
}

<Button backgroundColor="red" label="Click here" onClick={() => alert("Pressed")} />

In the above example, you have destroyed the attributes label and backgroundColor, the others will be assigned to props; we can also use the spread operator to spend all that is in props for the element button.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.