β Example of Props in Action:
<Greeting name="Zia" />
π Example: Greeting.js
import React from "react";
function Greeting(props) {
return <h2>Hello, {props.name}!</h2>;
}
export default Greeting;
Step 2: Use the Component in App.js
(Passing Props)
import Greeting from "./Greeting";
function App() {
return (
<div>
<Greeting name="Zia" />
<Greeting name="Ali" />
</div>
);
}
export default App;
π Example: Welcome.js
import React, { Component } from "react";
class Welcome extends Component {
render() {
return <h2>Welcome, {this.props.username}!</h2>;
}
}
export default Welcome;
Step 2: Use the Component in App.js
import Welcome from "./Welcome";
function App() {
return (
<div>
<Welcome username="Zia" />
<Welcome username="Sarah" />
</div>
);
}
export default App;
You can pass multiple props to a component.
π Example: Passing Multiple Props
function UserInfo(props) {
return (
<div>
<h2>Name: {props.name}</h2>
<p>Age: {props.age}</p>
<p>City: {props.city}</p>
</div>
);
}
export default UserInfo;
Using the Component in App.js
<UserInfo name="Zia" age="25" city="Lahore" />
<UserInfo name="Ali" age="30" city="Karachi" />
If a prop is not provided, you can set a default value using defaultProps
.
π Example: Setting Default Props
function Profile(props) {
return <h2>User: {props.username}</h2>;
}
Profile.defaultProps = {
username: "Guest",
};
export default Profile;
App.js
<Profile username="Zia" />
<Profile />
Instead of using props.name
, you can destructure props for cleaner code.
π Example: Destructuring Props
function Product({ name, price }) {
return (
<div>
<h2>Product: {name}</h2>
<p>Price: ${price}</p>
</div>
);
}
export default Product;
Using the Component in App.js
<Product name="Laptop" price="999" />
<Product name="Phone" price="599" />
You can pass functions as props to child components.
π Example: Passing a Function as a Prop
function Button({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
export default Button;
Using the Component in App.js
import Button from "./Button";
function App() {
const handleClick = () => {
alert("Button Clicked!");
};
return (
<div>
<Button onClick={handleClick} />
</div>
);
}
export default App;
import Button from "./Button";
function App() {
const handleClick = () => {
alert("Button Clicked!");
};
return (
<div>
<Button onClick={handleClick} />
</div>
);
}
export default App;
defaultProps
for fallback values.Props are a fundamental concept in React that help build scalable and modular applications! π