01 December 2024
Props (short for properties) are used to pass data from a parent component to a child component. Props are read-only, meaning they cannot be modified by the child component receiving them.
Define props in the parent component
function Parent() {
const name = "John";
return <Child name={name} />;
}
Access props in the child component
function Child(props) {
return <h1>Hello, {props.name}!</h1>;
}
Destructure props for cleaner syntax
function Child({ name }) {
return <h1>Hello, {name}!</h1>;
}
function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
function App() {
const handleClick = () => alert("Button clicked!");
return <Button label="Click Me" onClick={handleClick} />;
}