Components and Props

Use one component twice with different props. Follow React as it calls the same function once for each use.

React · beginner · 6 min · 9 steps · free

What you'll learn

Props.jsx

function Greeting({ name, emoji }) {
  const message = `Hello, ${name}!`;
  return (
    <p>
      {emoji} {message}
    </p>
  );
}

export default function App() {
  return (
    <div>
      <Greeting name="Ada" emoji="👋" />
      <Greeting name="Linus" emoji="🐧" />
    </div>
  );
}

Step by step

  1. React renders App, the top component.
  2. App returns JSX that uses Greeting twice, with different attributes. For a component, these attributes are called props.
  3. React calls Greeting with the props from the JSX: name = "Ada", emoji = "👋". The { name, emoji } in the parameter list unpacks them.
  4. Inside, Greeting is plain JavaScript: message = "Hello, Ada!".
  5. Greeting returns JSX: a description of what the screen should show, <p>👋 Hello, Ada!</p>. React has not changed the page yet.
  6. The same function runs again for the second <Greeting>, now with name = "Linus". Each use of a component is its own call, with its own props.
  7. message = "Hello, Linus!".
  8. Greeting returns JSX: a description of what the screen should show, <p>🐧 Hello, Linus!</p>. React has not changed the page yet.
  9. React builds the page from both results: two paragraphs from one component.

Common mistakes

Best practices

Key takeaways

Check yourself

<Greeting name="Ada" /> passes what to Greeting?

Answer: { name: "Ada" }. Props are one object.

Can Greeting change its name prop?

Answer: No, props are read-only. Only the parent decides its props.

·

More in Components and JSX