Props In ReactJS

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:

John
Age: 20
Course: 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

PropsState
Passed from parent to childManaged within the component
Read-onlyCan be updated using setState or useState
Used to pass dataUsed to store and manage changing data

Leave a comment