-1

I understand the concept of key in a loop on basic level. But my html is such that I am getting confused. Here's the loop I need help in placing the key at. key=product.id ALso, if we have selected one of the div, how do we change it from bg-success to bg-primary?

   {products.map(product => (
                                <div className="col-md-6 col-sm-12 col-xs-12">
                                    <div className="card rounded bg-success p-5 my-3 mr-3 text-center">
                                        <h4>{product.title}</h4>
                                        <h1 className="price">${product.price}</h1>
                                        <ul className="no-disk">
                                            <li key={product.id}>{product.month_count}</li>
                                            <li>{product.time} Package</li>
                                        </ul>
                                        <img className="img-responsive " src="images/store.png" />
                                    </div>
                                </div>
                            ))}
Sakshi
  • 73
  • 3
  • 12

1 Answers1

0

It should be noted that React will advise against the method below due to what keys do for repeated React components.

When you bring in data of some sort, maybe make sure that each index has its own ID.

In any case, map is an Array method that allows you to get the index and the element at the index, so the below approach will work, but it should be used sparingly.

   {products.map((product,id) => (
                                <div className="col-md-6 col-sm-12 col-xs-12">
                                    <div className="card rounded bg-success p-5 my-3 mr-3 text-center">
                                        <h4>{product.title}</h4>
                                        <h1 className="price">${product.price}</h1>
                                        <ul className="no-disk">
                                            <li key={product.id}>{product.month_count}</li>
                                            <li>{product.time} Package</li>
                                        </ul>
                                        <img className="img-responsive " src="images/store.png" />
                                    </div>
                                </div>
                            ))}
Justin Rice
  • 1,111
  • 12
  • 13
  • how do we check if one div is selected? then change it from bg-success to bg-primary? have to do it via react js, not via javascript – Sakshi Jul 31 '20 at 01:47
  • got it, the id is the index that you mentioned above!! used it for if else inside like this : index == '0' ? div of primary : div of success – Sakshi Jul 31 '20 at 02:17
  • 1
    This is something I would definitely use a hook for. React hooks allow us to hold state much closer to smaller components: https://reactjs.org/docs/hooks-intro.html – Justin Rice Jul 31 '20 at 02:55