Destructuring props
When working with React, you should know how JavaScript destructuring works. Because React's props are passed in as a JavaScript object, you can destructure it. Meaning, instead of declaring single function argument called props
, you can instead pull the values directly off the object.
How does this magic work? Well, you simply take whatever javascript key you want to pull into your current scope, insert it between curly braces, and that variable now becomes the value of that key in the object. We have three examples of this here.
First, we declare a user
object at the top of the file. It is just a regular JavaScript object with a key name
and value as Bill
. We want to render this user's name in our app, but we don't want to have to type user.name
. Instead- we destructure. We pull the name
off the object, but then we also rename that to be userName
. This syntax gets some getting used to, but this is called a destructuring assignment.
Next, we render a User component with a name prop set to userName. Since props are collected as an object argument to the component function, we destructure the name off that object in the function arguments.
We also destructure role
off the props, but we didn't pass that prop in! So we can default the prop value inside the object using the equals operator. role="pirate"
will set the role value to pirate
when the role is undefined, as it is in Bill's case.
const crew = [{ name: "Joe" }, { name: "Mark" }, { name: "Bob" }]; const user = { name: "Bill" }; // destructuring the props to pull name function User({ name, role = "pirate" }) { return ( <div> {name}: {role} </div> ); } export default function App() { // destructuring assignment const { name: userName } = user; return ( <div> <h1> 🏴☠️ The Captain's Crew </h1> <h2> Users </h2> <User name={userName} /> </div> ); }