DEV Community

chantastic
chantastic

Posted on

Make React Components as Re-usable as HTML Elements

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
Enter fullscreen mode Exit fullscreen mode

We use this feature to define variables for incoming props:

function  Pokemon({ name }) {
  /* ...now we can use `name`... */
}
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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`... */
}
Enter fullscreen mode Exit fullscreen mode

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} />
Enter fullscreen mode Exit fullscreen mode

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>
}
Enter fullscreen mode Exit fullscreen mode

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

  1. Use object destructuring assignment to get the name property from props
  2. Use rest paramaters (...) to assign the remaining values to variable named props or rest
  3. Use JSX Spread attributes syntax to assign all of the props (or rest) to the h1 React Element
  4. Test you work by adding an id, class, data-attribute, or anything you like

Follow the 🧵 on Twitter:

Subscribe on YouTube:

Top comments (1)

Collapse
 
davidgfriedman profile image
David G Friedman

Interesting review, though I'm trying to tech myself J's and react so the ...Rest was new to me. Btw, you keep using assiNGment in places instead of assiGNment, I think. I can't wait to read next segments.