What Does …Props Mean in React?

Even though it looks intimidating at first, ...props allows us pass props (data) to components without listing them out individually.

TL;DR version

export default function App() {
  const data = {
    title: "My awesome app",
    greeting: "Hi!",
    showButton: true
  };

  return <Header {...data} />;
}

function Header(props) {
  return (
    <nav>
      <h1>{props.title}</h1>
      <h2>{props.greeting}</h2>
      {props.showButton && <button>Logout</button>}
    </nav>
  );
}

If we have the data that we want to pass as props in an object, it allows us to spread them out as individual props by using the ...props syntax.

This syntax is also referred to as the spread operator and is a JavaScript (ES6) feature, not a React feature.

The standard way to pass props would be to list them out individually:

export default function App() {
  return <Header title="My awesome app" greeting="Hi!" showButton />;
}

function Header(props) {
  return (
    <nav>
      <h1>{props.title}</h1>
      <h2>{props.greeting}</h2>
      {props.showButton && <button>Logout</button>}
    </nav>
  );
}

When should you use it?

Consider using this pattern whenever you have a great deal of props to pass down to a child component and you do not want to list out each of the props individually.

It may harder to figure what exactly is being passed to a component, but you can decide whether this approach works for your app.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts