Components and Props

Destructuring Props

Destructing props can be totally intimidating when your first starting out in your Software Engineer career. Setting up the wireframe and creating the component is so easy! Right when its time to write code its like biting fingernails but rest assure you just like I started getting the hang of it you will too!

lets talk about props. Props are passed as an object inside of functional components. This usually happen inside the function parameter or somewhere inside the body.

import React from 'react';

// Without destructuring
function ZodiacSign = (props) => {
  return <div>{props.name}</div>;
};

// With destructuring
function ZodiacSign = ({ name }) => {
  return <div>{name}</div>;
};

In the code above

  1. Zodiac Sign is declared as a component without destructuring props is being passed down as an argument and returning the name property using prop.name.

  2. With destructuring we are able to pass name object as an argument and return the name object.

lets look at another example

import React from 'react';

// Destructuring props within the function parameters
const User = ({ name, age }) => {
  return (
    <div>
      <h2>Name: {name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}

export default User;

And then, in your main component or wherever you're rendering the User component, you pass props like this:

import React from 'react';
import User from './User';

const App = () => {
  return (
    <div>
      <h1>User Details</h1>
      {/* Passing props to User component */}
      <User name="John Doe" age={30} />
    </div>
  );
}

export default App;
  • The User component destructures the name and age props directly in the function parameters. This is a common pattern in functional components.

  • In the App component, when rendering User, you're passing props (name and age) directly to it.

Destructuring props in this manner is a concise way to extract specific properties from the props object passed to a component, making your code cleaner and easier to read.

I know it can be intimidating at first but you go this!