Props in React
Subject: React
What are Props?
Props (short for properties) are a way of passing data from one component to another in React โ specifically from a parent to a child component.
They allow you to make components reusable and dynamic, by feeding them custom data that they can render or use in logic.
๐ง Why Use Props?
- To make components flexible and reusable
- To communicate between components
- To customize behavior or content
๐ How Props Work (Concept Flow)
๐งฑ Basic Example
๐งฉ Parent Component:
๐งฉ Child Component (Greeting.js):
๐งพ Output:
๐ง Accessing Props
Props are passed as an object to the component:
You can also destructure for cleaner syntax:
๐ง Passing Multiple Props
๐ Props are Read-Only
You cannot change a prop inside a component. If you try to do this:
Props are meant to receive data, not modify it.
๐งช Dynamic Rendering with Props
You can pass props in loops:
๐ฏ Real-Life Analogy
Think of a component as a function, and props as its arguments:
Similarly:
๐ง Best Practices
- โ Always keep props immutable
- โ Use destructuring for cleaner syntax
- โ Use PropTypes or TypeScript to enforce prop types (optional)
๐ ๏ธ BONUS: Default Props (Optional Values)
๐ Summary
Feature | Explanation |
---|---|
What are Props? | Data passed from parent to child |
Direction | Unidirectional (Top to Bottom) |
Syntax | <Component propName="value" /> |
Access | Via props.propName or destructuring |
Modifiable? | โ No, they are read-only |
Purpose | Make components reusable and dynamic |
Advertisement Slot 1
Advertisement Slot 2