N
N
nivaech2019-09-10 01:35:21
JavaScript
nivaech, 2019-09-10 01:35:21

How to check if an object is in an array in JSX?

There is a page with products that can be added to the cart, cart.
cart - a separate state array with objects to which the selected products are added.
I want to make a condition under which the presence of a product in the cart would be checked, and if it is there, then the corresponding phrase would be displayed on the product page.
The condition is this. It checks if there is an item in the array with the corresponding id, and if so, a certain label is rendered.

<div>
                          {
                            cart.find(item => (item.id === id) ?
                              <p>I am in</p>
                              :
                              <p>I am not in</p>
                            )
                          }
                      </div>

But it doesn't work. I catch an error:
Objects are not valid as a React child (found: object with keys {id, title, price, category, type, description}). If you meant to render a collection of children, use an array instead.
How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-09-10
@nivaech

<p>{cart.find(item => item.id === id) ? 'я есть' : 'меня нет'}</p>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question