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
Appcomponent is passing theuserNamevariable as a prop to theGreetingcomponent.The
Greetingcomponent receives thenameprop 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
Appcomponent sends thenameandpriceof the product as props to theProductCardcomponent.The
ProductCardcomponent 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
Appcomponent passes ahandleClickfunction as a prop to theActionButtoncomponent.The
ActionButtoncomponent executes theonClickfunction 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
Appcomponent passes multiple pieces of user information (name, age, and occupation) as props to theUserProfilecomponent.The
UserProfilecomponent 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.
Comments
Join the discussionNo comments yet. Be the first to comment.