Kodokon kodokon.com

Props: passing data to a component

Learn how to make your components reusable by passing data to them through props.

7 min · 3 questions

Open this lesson in Kodokon

A component that always displays the same thing isn't very useful. Props (short for "properties") are the data you pass to a component, exactly like a function's arguments. Think of an invitation card: the template is the same for everyone, only the guest's first name changes. The component is the template, the prop is the first name.

JSX
function Greeting(props) {
  return <p>Hello, {props.name}!</p>;
}

function App() {
  return (
    <div>
      <Greeting name="Lea" />
      <Greeting name="Karim" />
    </div>
  );
}
One component, two different outputs

In App, you write name="Lea" like an HTML attribute: React gathers all these values into an object, which the component receives under the name props. You then read props.name inside curly braces. In practice, you often destructure the props directly in the function's parentheses: function Greeting({ name }). One more important point: text goes between quotes, but everything else (numbers, booleans, arrays) goes between curly braces.

JSX
function ProfileCard({ name, age }) {
  return (
    <div>
      <h3>{name}</h3>
      <p>{age} years old</p>
    </div>
  );
}

function App() {
  return <ProfileCard name="Nadia" age={31} />;
}
Destructured props; the number goes between curly braces

That is the whole power of props: a social network doesn't write one component per post, it writes a single Post component and passes it different props millions of times. You write the template once, you use it everywhere.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What are props for?
    • Passing data from a parent component to a child
    • Storing data that changes over time
    • Applying CSS styles to a component
  2. How do you pass the number 25 to a Profile component?
    • <Profile age="25" />
    • <Profile age={25} />
    • <Profile age=25 />
  3. Can a component modify the props it receives?
    • Yes, as long as it does so inside the return
    • Yes, but only strings
    • No, props are read-only