Props
Props are used to pass data from a parent component to a child component
function Parent(props) {
return <h1>Hello, {props.name}!</h1>;
}
function Child() {
return <Parent name="John" />;
}
Destructuring props
function Greeting({ name, age }) {
return (
<div>
<h1>Hello,I'm {name}!</h1>
<p>I am {age} years old.</p>
</div>
);
}
function App() {
return <Greeting name="Kiruthiga" age={21} />;
}
What are the ways to use props
- Passing Strings
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return <Welcome name="Alice" />;
}
- Passing Numbers
function Student({ marks }) {
return <p>Marks: {marks}</p>;
}
function App() {
return <Student marks={95} />;
}
- Passing Boolean Values
function User({ isLoggedIn }) {
return (
<h1>{isLoggedIn ? "Welcome!" : "Please Login"}</h1>
);
}
function App() {
return <User isLoggedIn={true} />;
}
- Passing Arrays
function Fruits({ items }) {
return (
<ul>
{items.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}
function App() {
return <Fruits items={["Apple", "Banana", "Orange"]} />;
}
- Passing Objects
function Employee({ emp }) {
return (
<div>
<h2>{emp.name}</h2>
<p>{emp.role}</p>
</div>
);
}
function App() {
const employee = {
name: "John",
role: "Developer",
};
return <Employee emp={employee} />;
}
- Passing Functions
function Button({ handleClick }) {
return <button onClick={handleClick}>Click Me</button>;
}
function App() {
function greet() {
alert("Hello!");
}
return <Button handleClick={greet} />;
}
Top comments (0)