Skip to content

Latest commit

 

History

History
64 lines (40 loc) · 2.61 KB

props.md

File metadata and controls

64 lines (40 loc) · 2.61 KB

Props: Passing Data with Style 📦

Props are like the magic mail carriers of React! They allow you to send data from one component to another, just like sharing a secret message with a friend. Let’s dive into the world of props and see how they work!

Meet Mia and Leo:

Mia: "Hey Leo, how do we share information between our components?"

Leo: "Ah, that’s easy! We use props! Think of them as the gifts we give to our components. 🎁"

What Are Props?

  • Props (short for properties) are how we pass data from a parent component to a child component.
  • They can be anything from strings and numbers to functions and even entire components!

How to Use Props

  1. Sending Props: You can send props to a child component by adding them like attributes in HTML:

    <ChildComponent name="Mia" age={10} />
  2. Receiving Props: In the child component, you can access these props like this:

    const ChildComponent = (props) => {
      return <div>{props.name} is {props.age} years old!</div>;
    };
  3. Destructuring Props: To make your code cleaner, you can destructure props directly in the function parameters:

    const ChildComponent = ({ name, age }) => {
      return <div>{name} is {age} years old!</div>;
    };

    This way, you don’t have to write props.name and props.age every time!

Why Use Props?

  • Reusability: Props make your components reusable! You can create a single component and use it in many places with different data. It’s like having a superhero costume you can change to fit any occasion! 🦸‍♂️

  • Dynamic Rendering: By passing different props, you can change how a component looks and behaves without rewriting code. It’s like customizing your pizza with different toppings! 🍕

Props vs. State

  • Props: Passed from parent to child, immutable (cannot be changed by the child).
  • State: Managed within a component, mutable (can be changed by the component itself).

Mia: "So, it’s like props are the toppings on our pizza, and state is the dough!"

Leo: "Exactly! And just like you wouldn’t want to mix up your pizza toppings, keeping props and state separate helps keep our components clean and organized!" 🍕✨


Fun Fact! 🎉

Did you know that using props is like a game of telephone? Just like passing a message along, props allow data to travel from one component to another, making your app dynamic and interactive!


Navigation

Previous: Functional Components vs. Class Components | Next: State: Managing Component Data