Simple Examples of Using Props in React
Here are some simple, real-world examples of components using props in React:
1. Greeting Component Example (Passing a User’s Name as a Prop)
This example demonstrates how you can pass a user’s name from a parent component to a child component to create a personalized greeting.
// Parent Component
function App() {
const userName = "Alice";
return (
<div>
<Greeting name={userName} />
</div>
);
}
// Child Component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default App;
The
App
component is passing theuserName
variable as a prop to theGreeting
component.The
Greeting
component receives thename
prop and displays "Hello, Alice!".
2. Product Card Example (Passing Product Information as Props)
In this example, the parent component passes product information (name and price) to a ProductCard
component to display it.
// Parent Component
function App() {
const product = {
name: "Laptop",
price: 1200
};
return (
<div>
<ProductCard name={product.name} price={product.price} />
</div>
);
}
// Child Component
function ProductCard(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Price: ${props.price}</p>
</div>
);
}
export default App;
The
App
component sends thename
andprice
of the product as props to theProductCard
component.The
ProductCard
component displays the product name and price.
3. Button Component Example (Passing a Function as a Prop)
Here’s how you can pass a function as a prop to handle a button click event in the child component.
// Parent Component
function App() {
function handleClick() {
alert("Button was clicked!");
}
return (
<div>
<ActionButton onClick={handleClick} />
</div>
);
}
// Child Component
function ActionButton(props) {
return (
<button onClick={props.onClick}>
Click Me
</button>
);
}
export default App;
The
App
component passes ahandleClick
function as a prop to theActionButton
component.The
ActionButton
component executes theonClick
function when the button is clicked.
4. User Profile Example (Passing Multiple Props)
This example shows how to pass multiple props, such as name, age, and occupation, to a UserProfile
component.
// Parent Component
function App() {
const user = {
name: "John Doe",
age: 30,
occupation: "Engineer"
};
return (
<div>
<UserProfile name={user.name} age={user.age} occupation={user.occupation} />
</div>
);
}
// Child Component
function UserProfile(props) {
return (
<div>
<h2>Name: {props.name}</h2>
<p>Age: {props.age}</p>
<p>Occupation: {props.occupation}</p>
</div>
);
}
export default App;
The
App
component passes multiple pieces of user information (name, age, and occupation) as props to theUserProfile
component.The
UserProfile
component displays the user's details.
In Short:
These examples illustrate how props are used to pass data (strings, numbers, objects, or even functions) between components, enabling dynamic rendering and user interactions in React applications.