Passing Data with Props in React
In React, props (short for properties) are a powerful mechanism for customizing and passing data from a parent to a child component. This feature allows us to create reusable and flexible components within the app.
Passing Props
Imagine we're building an online store.
In this scenario, we have a main component called App
, and we want to display product information using a Product
component. We can pass the product name and price as props from App
to Product
.
Here's how it's done in practice:
// Parent Component (`App`)const App = () => (<><h1>Online Store</h1><Product name="Green iguana" price={579} /></>);
In the App
component, we include the Product
component and pass it the props: name
with the value "Green iguana"
and price
with the value 579
.
Receiving and Using Props
Now, let's take a look at the Product
component, which receives these props:
// Child Component (`Product`)const Product = (props) => (<><p>Product name: {props.name}</p><p>Price: ${props.price}</p></>);
In the Product
component, we define it to accept a single argument called props
. Inside the component, we can access the values of these props using the dot (.
) notation followed by the property name (e.g., props.name
and props.price
).
Practical Use
With this approach, we've created a Product
component that can be reused with different product information multiple times. We can easily customize the text content of each Product
component by providing different props.
<Product name="Yellow cheetah" price={1099} /><Product name="Panda" price={449} />
Now we have the flexibility to display various product details using the same Product
component.
Full App Code:
1. What is the purpose of props in React?
2. What is the advantage of using props in React?
¡Gracias por tus comentarios!