Passing Props in React
Expert-Level Explanation
Passing props in React is the process of transferring data from a parent component to a child component. Props are immutable within the child component, meaning they should not be modified directly. This unidirectional data flow ensures that the data in the application is stable and predictable. Props can include various types of data, such as numbers, strings, functions, objects, and even other React components. They make components reusable and dynamic by allowing them to behave differently based on the input they receive.
Creative Explanation
Imagine props like postcards sent from a town (parent component) to a villager (child component). Each postcard contains information or messages that the villager uses but cannot alter. For different villagers, the town sends different postcards, customising the message for each recipient. Similarly, in React, different data can be passed as props to different instances of the same component, allowing for tailored rendering and behaviour.
Practical Explanation with Code
Here's how props are typically passed in React:
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
export default App;
In this example, theApp
component is passing a different name
prop to each Greeting
component. TheGreeting
component then renders a personalised message based on the received prop.
Real-World Example
On an e-commerce website, a ProductCard
component displays product information. The parent component (say, ProductList
) passes the details of each product (like the title, image, and price) as props toProductCard
. EachProductCard
displays the information it receives, allowing the ProductList
to render a grid of different product cards.