DEV Community

Cover image for Destructuring Props in React.
R-Villar
R-Villar

Posted on

Destructuring Props in React.

Once you begin your journey of learning React, one of the first things you will learn about is Props. If you are already familiar with how functions and arguments work in JavaScript, grasping Props will not be difficult.

What are Props?

Props are arguments passed into React components, Props are also passed to components by HTML attributes.

What is Destructuring?

It is a convenient way of accessing the multiple properties stored in objects and arrays.

Let's get started with an example.

function App() {
  const car = {
    brand: 'Jeep',
    model: 'gladiator',
    year: '2022',
    color: 'red',
    price: '37,000',
  };

  return (
    <div>
      <cars car={car} />
    </div>
  )
}

function displayCar({car}) {
  return (
    <div>
      <p>My car's brand is, {car.brand}</p>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Here we have our car object inside of App, we pass it as a prop to the component Cars. Inside of the Cars component we now have access to the car object.

function displayCar({car}) {
  return (
    <div>
      <p>My car's brand is, {car.brand}</p>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

As you can see above we now can use dot notation to access the information, but what if we can destructure the prop and clean up the code.

const {brand, model, year, color, price} = car

we can destructure the car object and our code will be a bit cleaner and mode readable.

function displayCar({car}) {
  const {brand, model, color} = car
  return (
    <div>
      <p>My car's brand is, {brand}</p>
      <p>My car's model is, {model}</p>
      <p>My car's color is, {color}</p>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

This will be what you will see on screen.

My car's brand is, Jeep
My car's model is, gladiator
My car's color is, red

From a beginners point of view this is one of the simple ways to destructure but it is far from the only one, things can get complicated really quickly when the amount of data you are working with is substantial.

resources:
https://reactjs.org/docs/components-and-props.html
react image:
https://mobile.twitter.com/reactjs

Top comments (0)