What are props in React
In React, props (short for "properties") are a way to pass data from a parent component to a child component. They are read-only and help make components reusable and dynamic.
Key Characteristics of Props:
Immutable – Props cannot be modified by the child component.
Passed Down – Data flows from parent to child (unidirectional).
Can Be Anything – Props can be strings, numbers, arrays, objects, functions, or even other React components.
Example:
// Parent Component function App() { return <Greeting name="Alice" age={25} />; } // Child Component (receives props) function Greeting(props) { return ( <h1>Hello, {props.name}! You are {props.age} years old.</h1> ); }
Using Destructuring for Cleaner Code:
function Greeting({ name, age }) { return <h1>Hello, {name}! You are {age} years old.</h1>; }
Passing Functions as Props:
function Parent() { const handleClick = () => alert("Button clicked!"); return <Child onClick={handleClick} />; } function Child({ onClick }) { return <button onClick={onClick}>Click Me</button>; }
Props vs. State:
Props | State |
---|---|
Passed from parent | Managed within the component |
Read-only | Mutable (via setState or useState ) |
Used for configuration | Used for dynamic data |
Special Props:
children
: Accesses content between component tags.function Card({ children }) { return <div className="card">{children}</div>; } // Usage: <Card> <h1>Title</h1> </Card>
Props are fundamental for component communication in React, enabling reusable and modular UI design.