Props and Component Communication
In React, Props (short for properties) are the primary way to pass data from a parent component down to a child component. They are read-only and help make your components reusable and dynamic.
1. Passing and Receiving Props
You pass props to a component just like you pass attributes to an HTML tag. In the child component, these props are received as a single object argument.
JavaScript
// Parent Component
function App() {
return <Greeting name="Ashish" message="Welcome to the React Course!" />;
}
// Child Component
function Greeting(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>{props.message}</p>
</div>
);
} 2. Destructuring Props
To make the code cleaner, developers often use JavaScript destructuring to extract values directly in the function signature.
JavaScript
function Greeting({ name, message }) {
return (
<div>
<h1>Hello, {name}!</h1>
<p>{message}</p>
</div>
);
} 3. Lifting State Up (Child to Parent)
Props only flow downwards. To send data from a child back to a parent, you pass a callback function as a prop. The child then calls this function to "talk" to the parent.
JavaScript
function Parent() {
const handleChildData = (data) => {
console.log("Data from child:", data);
};
return <Child onButtonClick={handleChildData} />;
}
function Child({ onButtonClick }) {
return (
<button onClick={() => onButtonClick("Hello Parent!")}>
Send Data to Parent
</button>
);
} Note: Props are immutable. A component should never modify its own props; it should only read them and render UI based on them.