What are Props in React?
Props (short for properties) are a way to pass data from a parent component to a child component in React. They make components reusable and dynamic.
Key Features of Props
- Props are read-only (immutable).
- They are passed from parent to child.
- They can contain any JavaScript value:
- Strings
- Numbers
- Booleans
- Arrays
- Objects
- Functions
- JSX
Example 1: Passing a String Prop
Parent Component (App.js)
import Welcome from "./Welcome";function App() { return ( <div> <Welcome name="Alice" /> </div> );}export default App;
Child Component (Welcome.js)
function Welcome(props) { return <h1>Hello, {props.name}!</h1>;}export default Welcome;
Output:
Hello, Alice!
Example 2: Destructuring Props
Instead of writing props.name, you can destructure the props.
function Welcome({ name }) { return <h1>Hello, {name}!</h1>;}
Example 3: Passing Multiple Props
function App() { return ( <Student name="John" age={20} course="React" /> );}
function Student({ name, age, course }) { return ( <div> <h2>{name}</h2> <p>Age: {age}</p> <p>Course: {course}</p> </div> );}
Output:
JohnAge: 20Course: React
Example 4: Passing a Function as a Prop
Parent
function App() { const greet = () => { alert("Hello!"); }; return <Button onClick={greet} />;}
Child
function Button({ onClick }) { return <button onClick={onClick}>Click Me</button>;}
When the button is clicked, an alert saying “Hello!” appears.
Example 5: Passing an Object
function App() { const user = { name: "Emma", age: 25 }; return <Profile user={user} />;}
function Profile({ user }) { return ( <div> <h2>{user.name}</h2> <p>{user.age}</p> </div> );}
Why Use Props?
- Reuse components with different data.
- Pass data between components.
- Keep components modular and maintainable.
- Improve code readability.
Props vs State
| Props | State |
|---|---|
| Passed from parent to child | Managed within the component |
| Read-only | Can be updated using setState or useState |
| Used to pass data | Used to store and manage changing data |
