0
0
ReactHow-ToBeginner · 3 min read

How to Destructure Props in React: Simple Syntax and Examples

In React, you can destructure props directly in the function parameter list or inside the function body using JavaScript object destructuring. This lets you extract specific prop values by name, making your code cleaner and easier to read.
📐

Syntax

You can destructure props in two main ways in a React functional component:

  • In the function parameter: Extract props directly when defining the function.
  • Inside the function body: Use object destructuring to extract props from the props object.

This uses JavaScript object destructuring syntax.

jsx
function MyComponent({ title, subtitle }) {
  return <div>
    <h1>{title}</h1>
    <h2>{subtitle}</h2>
  </div>;
}

// Or inside the function
function MyComponent(props) {
  const { title, subtitle } = props;
  return <div>
    <h1>{title}</h1>
    <h2>{subtitle}</h2>
  </div>;
}
💻

Example

This example shows a React component that destructures props in the function parameter to display a greeting message with a name and age.

jsx
import React from 'react';

function Greeting({ name, age }) {
  return <p>Hello, my name is {name} and I am {age} years old.</p>;
}

export default function App() {
  return <Greeting name="Alice" age={30} />;
}
Output
Hello, my name is Alice and I am 30 years old.
⚠️

Common Pitfalls

Common mistakes when destructuring props include:

  • Trying to destructure props that are not passed, causing undefined errors.
  • Using incorrect prop names that don't match what is passed.
  • Forgetting to destructure and trying to access props directly without props. prefix.

Always ensure the prop names match and provide default values if needed.

jsx
function Wrong({ title }) {
  // If 'title' prop is not passed, this will be undefined
  return <h1>{title && title.toUpperCase()}</h1>;
}

// Correct with default value
function Correct({ title = 'Default Title' }) {
  return <h1>{title.toUpperCase()}</h1>;
}
📊

Quick Reference

Destructuring MethodSyntax ExampleNotes
In function parameterfunction Comp({ prop1, prop2 }) { ... }Clean and concise
Inside function bodyconst { prop1, prop2 } = props;Useful if you need full props object
Default valuesfunction Comp({ prop1 = 'default' }) { ... }Avoids undefined errors

Key Takeaways

Destructure props directly in the function parameter for cleaner code.
Use object destructuring inside the function if you need the full props object.
Always match prop names exactly and consider default values to avoid errors.
Destructuring makes your component code easier to read and maintain.