B
B
bmg012020-11-04 22:15:06
React
bmg01, 2020-11-04 22:15:06

Props, React JS arrays don't do a favor?

Hello
, there is such a component

function Main() {
   const database = [
        {
            id: 1,
            name: "MacBook",
            price: 100000,
            bought: false,
            rating: 5,
        }]
  return (
        <div className="main">
            {database.map((product) => {
                return <Maincont product={product}/>
            })}
        </div>
    )
}
И есть еще такой компонент <Maincont/>
  function Maincont(props){
    return (
        <div className ="card">
            <div className="card-info">
                <div className="card-name">{?}</div>
                <div className="card-price">{?}</div>
            </div>
        </div>
}


now the question is, as you already understood, things with props are here, I don’t know how to make it so that from the datebase variable name and price are displayed in the final result

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NewD16, 2020-11-04
@NewD16

If I understand the question correctly, then this problem has two solutions. The props you get in the Maincont component is an object that should have a product field (according to this post <Maincont product={product}/>). This means that to get the name and price of the product object, you just need to refer to them: props.product.name and props.product.price. But there is a more practical way - with the help of destructuring, you can pass in props in the form of {product}. Now you can access your product object directly in the component - . But it would be even more logical in this situation to pass not the product object, but its fields!function Maincont({product}){...}

<Maincont name={product.name} price={product.price}/>

, and the component itself will look like this: And the last thing - to write it even cooler, you can also pass props using destructuring like this: . True, with this approach, you pass all the fields of the object, and only two seem to be used in the component, so the most logical option isfunction Maincont({name, price}){...}
<Maincont {...product} />
<Maincont name={product.name} price={product.price}/>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question