Component Props in React
In the previous lesson we output several product instances:
function App() {
return <div>
<Product />
<Product />
<Product />
</div>;
}
So far, every call to the product tag displays the same thing. Now let's make each product unique.
Let's say, for example, that each product should have a name and a price. Let's make it so that each call of the tag with the product displays the product with its name and price, formatted in the layout we need.
To do this, we need to take several steps.
To begin with, when calling a tag with a product, we will write two attributes in this tag: the attribute name with the name of the product and the attribute cost with the price, like this:
function App() {
return <div>
<Product name="product1" cost="100" />
<Product name="product2" cost="200" />
<Product name="product3" cost="300" />
</div>;
}
The names and values of these attributes will be passed as an object to the first parameter of the constructor function of our Product component:
function Product(props) {
console.log(props); // object with keys name and cost return <p>
product
</p>;
}
The parameter name can be anything, but in React it is customary to call it props. In fact, this is not just a parameter name, but an important concept in React.
The gist of this concept is this: when a component tag is called, you can write attributes with data into that tag. This data will end up in the props of the component. The component can then use this data, for example, to create the desired layout.
Let's do this:
function Product(props) {
return <p>
name: <span>{props.name}</span>,
cost: <span>{props.cost}</span>
</p>;
}
It is more convenient and more common not to use the props object, but to immediately perform destructuring props directly in the function parameters:
function Product({ name, cost }) {
return <p>
name: <span>{name}</span>,
cost: <span>{cost}</span>
</p>;
}
Create a Employee component that displays employee data on the screen. Let this data be the last name, first name, middle name, and salary. Format this data in the layout you need. Display three employees with different data in the App component.