Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spread attributes and Destructuring props in Components

Spread attributes and Destructuring props in Components

How to use Spread attributes and Destructuring props in React Components


These are common Javascript patterns but what is the "right way" to use them with React specially in JSX.

Destructuring

Destructuring was added back in 2015. So you migt be familiar by now

let user = { name: 'Jhon' }
let { name } = user
let fruits = ['orange', 'apple']
let [first, second] = fruits

you can use them in React components

function SayHello(props) {
  return <div>Hello {props.name}!</div>
}

function SayHello({ name }) {
  return <div>Hello {name}!</div>
}

You can also collect the remaining props into an object

function SayHello({ name, ...rest }) {
  return <div>Hello {name}!</div>
}

the three dots take the remaining properties and assign them to the object rest

Spread

We can Spread Attributes over our components and DOM elements as well

function SayHello({ name, ...rest }) {
  return <div {...rest}>Hi {name}!</div>
}

We pass DOM attributes to Greeting and they'll be passed through to the div element

<SayHello name="Joni" id="my-id"  className="my-class" />

Do not forwarding non-DOM props to components. You have the power of separate component-specific props from DOM/platform-specific attributes

function SayHello({ name, ...platformProps }) {
  return <div {...platformProps}>Hi {name}!</div>
}

Things to keep in mind

Order matters for spread attributes

<SayHello name="Joni" id="my-id"  className="my-class" />
function SayHello({ name, ...platformProps }) {
  return <div className="my-class-original" {...platformProps}>Hi {name}!</div>
}

In this case the className props will override the class that the component already have. To fix it we could merge both of them and add it togheter or put the spread props before the class in the component like so

function SayHello({ name, ...platformProps }) {
  return <div {...platformProps} className="my-class-original">Hi {name}!</div>
}

To prevent from undefined showing up as a className, Use Javscript default values

function SayHello({ className = "", ...props }) {
  ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment