Learn React · 3/13

Props: Passing Data Around

5 min read

Props: Passing Data Around iprop_guide

Welcome back! So you've got your React components, but they're like islands, isolated and unaware of each other. How do you make them talk? That's where props come in, the postal service of the React world! 📮

1. What are Props? (Communicating between components)

Definition: In React, "props" is short for "properties" and is a mechanism for passing data from a parent component to a child component. This data flow is unidirectional, meaning it only goes from parent to child. Think of it as a one-way street for information.

The Problem: Imagine you have a UserProfile component. You want to display different users, but the name and profile picture are hardcoded. To show another user, you'd have to create a whole new component. That's not very efficient, is it?

The Solution: Props allow you to make your components reusable and dynamic. You can create a single UserProfile component and then pass different user data to it as props.

How it works under the hood: When React sees a component you've written, it takes all the attributes you've passed to it in JSX and bundles them into a single JavaScript object called props. This props object is then passed as an argument to your component function.

Here's a simple example:

jsx
// Parent Component
function App() {
  return <Greeting name="Alice" />;
}

// Child Component
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

In this example, the App component is the parent, and it's passing a name prop with the value "Alice" to the Greeting child component. The Greeting component then accesses this value using props.name.

Interesting Fact: Props are read-only. A component can never change the props it receives. This ensures a predictable data flow and makes your application easier to debug. It's like receiving a letter; you can read it, but you can't change what's written inside.

2. Passing Strings, Numbers, and Arrays

You're not limited to just passing strings. You can pass any JavaScript data type through props, including numbers, arrays, and even objects and functions!

Passing a String:
This is the most straightforward. You just enclose the string in double quotes.

jsx
<Greeting name="Bob" />

Passing a Number:
To pass a number (or any other JavaScript expression like a variable or an object), you need to use curly braces {}.

jsx
<Product price={25} />

If you were to pass it as a string (price="25"), it would be treated as text, not a number, which could lead to unexpected behavior in calculations.

Passing an Array:
Similarly, you pass arrays using curly braces. This is incredibly useful for rendering lists of items.

jsx
// Parent Component
function App() {
  const items = ['Apple', 'Banana', 'Cherry'];
  return <ShoppingList items={items} />;
}

// Child Component
function ShoppingList(props) {
  return (
    <ul>
      {props.items.map(item => <li key={item}>{item}</li>)}
    </ul>
  );
}

In this example, we're passing an array of items to the ShoppingList component. The child component then uses the map() function to iterate over the array and render each item as a list element.

3. The children Prop: Composing Components

Definition: props.children is a special prop that allows you to pass components or JSX as children to another component. This is a powerful feature for creating flexible and reusable components.

The Problem: Imagine you want to create a Card component that can have different content inside it. You could pass the content as a regular prop, but that can get messy and inflexible, especially with complex HTML structures.

The Solution: The children prop lets you place content directly between the opening and closing tags of your component, just like with standard HTML elements.

jsx
// Parent Component
function App() {
  return (
    <Card>
      <h2>Photo of the Day</h2>
      <img src="https://example.com/photo.jpg" alt="A beautiful landscape" />
      <p>This is a stunning photo of a mountain range at sunrise.</p>
    </Card>
  );
}

// Child Component
function Card(props) {
  return (
    <div className="card">
      {props.children}
    </div>
  );
}

Here, everything inside the <Card> tags in the App component is passed as props.children to the Card component and rendered inside the div.

Funny Exaggeration: Without props.children, creating reusable layouts would be like trying to build with LEGOs that are all glued together. You'd have to create a new, slightly different LEGO brick for every single variation. props.children is like getting a big box of individual bricks you can assemble in any way you want!

4. Destructuring Props for Cleaner Code

The Problem: As your components grow, you might find yourself repeatedly typing props.whatever, props.somethingElse, and so on. This can make your code verbose and harder to read.

The Solution: ES6 destructuring allows you to unpack values from objects into distinct variables. This makes your code more concise and readable.

How it works: Instead of taking the entire props object as an argument, you can destructure it right in the function's parameter list.

Without Destructuring:

jsx
function UserProfile(props) {
  return (
    <div>
      <h2>{props.name}</h2>
      <p>{props.email}</p>
    </div>
  );
}

With Destructuring:

jsx
function UserProfile({ name, email }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>{email}</p>
    </div>
  );
}

See how much cleaner that is? You immediately know what props this component expects just by looking at the function signature.

Industry Standard: Destructuring props is a widely adopted best practice in the React community because it improves code clarity and maintainability.

Pro Tip: You can also set default values for props right in the destructuring assignment. This is a great way to prevent errors if a prop isn't passed.

jsx
function Button({ text = 'Click Me', color = 'blue' }) {
  return <button style={{ backgroundColor: color }}>{text}</button>;
}

📚 Further Reading

Challenge

You are tasked with building a system to display a list of products. To do this, you will create three components: ProductCard, ProductList, and App.

1. The ProductCard Component

Create a function component named ProductCard.

  • It must accept props for name, price, inStock, an optional saleInfo, and children.
  • Use ES6 destructuring directly in the function signature to extract the props.
  • Provide a default value for the saleInfo prop: an empty object {}.
  • The component should render the following structure:
    • An <h2> displaying the product's name.
    • A <p> that displays the price. The format must be Price: $[price].
    • Immediately following the price text inside the same <p>, conditionally render a <span> with the text (On Sale!) but only if saleInfo.onSale is true.
    • A separate <p> that conditionally displays text: "In Stock" if inStock is true, and "Out of Stock" if inStock is false.
    • A <div> that renders the children prop passed to it.

2. The ProductList Component

Create a function component named ProductList.

  • It should use the products array provided in the initial code.
  • Map over the products array to render a ProductCard for each product object.
  • For each ProductCard, you must pass the name, price, inStock, and saleInfo properties from the current product object as props.
  • For each ProductCard, pass a <button>Buy Now</button> as its child.

3. The App Component

Create a function component named App that renders your ProductList component.

Expected result

Your code should render a list of four product cards. The final output should be a single parent element containing these cards, with each card displaying the product's details, stock status, sale status (if applicable), and a "Buy Now" button.

  • Laptop Card:

    • An <h2> with the text "Laptop".
    • A <p> with the text "Price: $1200" followed by a <span> with " (On Sale!)".
    • A <p> with the text "In Stock".
    • A <div> containing a <button> with the text "Buy Now".
  • Mouse Card:

    • An <h2> with the text "Mouse".
    • A <p> with the text "Price: $25".
    • A <p> with the text "Out of Stock".
    • A <div> containing a <button> with the text "Buy Now".
  • Keyboard Card:

    • An <h2> with the text "Keyboard".
    • A <p> with the text "Price: $75" followed by a <span> with " (On Sale!)".
    • A <p> with the text "In Stock".
    • A <div> containing a <button> with the text "Buy Now".
  • Monitor Card:

    • An <h2> with the text "Monitor".
    • A <p> with the text "Price: $300".
    • A <p> with the text "In Stock".
    • A <div> containing a <button> with the text "Buy Now".
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.