Out of the box, components are less flexible and re-usable than raw HTML Elements.
But we can fix that with a little JavaScript and JSX.
Object Destructuring Assingment
This is a JavaScript feature.
This allows you to assign local variables from object keys using a reverse object literal syntax.
let { name, base_experience } = { name: "Bulbasaur", base_experience: 64 };
console.log(name) // => "Bulbasaur"
console.log(base_experience) // => 64
We use this feature to define variables for incoming props:
function Pokemon({ name }) {
/* ...now we can use `name`... */
}
Rest Paramaters
Rest Paramaters is a JavaScript syntax for scooping up remaining properties โย where destructuring assingment is used:
let { name, ...rest } = { name: "Bulbasaur", base_experience: 64, height: 7 };
console.log(name) // => "Bulbasaur"
console.log(rest) // => { base_experience: 64, height: 7 }
We use this for collecting all the props that might be sent to a regular HTML Element:
function Pokemon({ name, ...hostProps }) {
/* ...now we can use `name` and `hostProps`... */
}
JSX Spread Attributes
This is as JSX feature.
JSX Spread Attributes lets of take an object and "spread" it's key/value pairs over a React Element.
These two examples are equivalent:
// JSX Spread Attributes
let hostProps = { id: "1", className: "pokemon", data-base-experience: 64 };
<h1 {...hostProps} />
// Individual Attributes assignements
<h1 id={1}, className="pokemon", data-base-experience={64} />
We use this to "spread" any and all props (that we don't care about) onto the React Element:
function Pokemon({ name, ...hostProps }) {
return <h1 {...hostProps}>{name}</h1>
}
Now, our component is just as re-usable as an HTML Element!
Phew ๐
Give it a try!
Open this CodeSandbox in a browser and explore object destructuring assignment, rest paramaters, and JSX Spread Attributes.
Assignment
- Use object destructuring assignment to get the
name
property fromprops
- Use rest paramaters (...) to assign the remaining values to variable named
props
orrest
- Use JSX Spread attributes syntax to assign all of the
props
(orrest
) to the h1 React Element - Test you work by adding an
id
,class
,data-attribute
, or anything you like
Follow the ๐งต on Twitter:
Subscribe on YouTube: