New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› React› Props and Composition

Props and Composition

💻 React

Pass data into components with props and compose small pieces into a page.

Lesson 2 of 9 Tutorial
0 of 9 completed

Props are the inputs of a component. They make one component reusable with different data.

By the end of this lesson you can:
  • Pass and read props.
  • Destructure props.
  • Compose components together.

Passing Props

Add attributes to the component and read them from the props object.

function Badge({ label, tone = "neutral" }) {
  return <span className={`badge badge-${tone}`}>{label}</span>;
}

function App() {
  return (
    <div>
      <Badge label="Free" />
      <Badge label="Premium" tone="gold" />
    </div>
  );
}

Props Are Read-Only

A component must never change its own props. If a value needs to change, the parent owns it and passes a new value.

Children

The children prop holds whatever is placed between the opening and closing tags. It is how layout components work.

function Card({ title, children }) {
  return (
    <section className="card">
      <h2>{title}</h2>
      {children}
    </section>
  );
}

<Card title="Results">
  <p>You passed 8 of 10 subjects.</p>
</Card>
Warning Do not pass a new object or array inline on every render if a child depends on it. It can cause unnecessary work.

Practice

  1. Create a Button component with label and onClick props.
  2. Use children to build a reusable Panel component.
  3. Render a list of three Badge components.

Hands-on exercise

Create a StudentCard component that accepts name, level and score.
Render three different students from an array.
Highlight the score when it is 70 or above.

Recap

Props pass data down the tree. Components never change props, and children make layout components flexible.

Example

function Badge({ label, tone = "neutral" }) {
  return <span className={`badge badge-${tone}`}>{label}</span>;
}

function App() {
  return (
    <div>
      <Badge label="Free" />
      <Badge label="Premium" tone="gold" />
    </div>
  );
}

Exercises

Exercise 1. Reusable student card Easy
Create a StudentCard component that accepts name, level and score.
Render three different students from an array.
Highlight the score when it is 70 or above.
React exercise-1.txt
Expected Output
Three cards, with high scores styled differently.

Lesson Nav

Lesson sections