Back to all posts

Destructuring of Props in ReactJS


The syntax function name({props}){} in React is a way to define a functional component that takes an object as its argument. This object is de-structured to extract the props property, which is then used within the component.

This pattern is particularly useful in React for passing data from parent components to child components.

Example Without Destructuring

function Greeting(props) {
 return <h1>Hello, {props.person.firstName}!</h1>;
}

Without destructuring, accessing the firstName property requires prefixing it with props.person., which can become cumbersome, especially when dealing with deeply nested objects or multiple props.

Practical Application in React Components

Functional Components

const Attraction = ({ auth, attraction: { id, name, image_url } }) => {
 return (
    <div key={id}>
      <img alt={name} src={image_url} />
      <h1>{name}</h1>
    </div>
 );
};

Class Components

class Attraction extends React.Component {
 render() {
    const { auth, attraction: { id, name, image_url } } = this.props;
    return (
      <div key={id}>
        <img alt={name} src={image_url} />
        <h1>{name}</h1>
      </div>
    );
 }
}