Props in React
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.
Key Features of Props
- Passed as an object to the component.
- Immutable (cannot be changed by the component receiving them).
- Used for dynamic data and reusability.
How to Pass Props Between Components
-
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>; }
Example of Props
function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
function App() {
const handleClick = () => alert("Button clicked!");
return <Button label="Click Me" onClick={handleClick} />;
}