Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Update a list with New Items But Ids might repeat

I have a stateful component which maintains 2 lists of different types. As an example, think in terms of cars. Each car has a make(and lets say it has unique makeId) and model(again with a unique modelId). Now my component first displays a list of makes, each having a key attribute whose value is makeId. Now upon click on a make, My stateful component updates the list with all the models(each having modelId as key attribute) of the selected make. Now it might happen that some make had the same numeric value of makeId as the numeric value of modelId now being rendered.(because makes and models go in different Relational tables). Will react face some issues while updating the list in this case?

Example:

Below is the comparison of old and new list.

<ul>
  <li key=1> Some Make X</li>
  <li key=2> Some Make Y</li>
</ul>


<ul>
  <li key=34> Some Model X</li>
  <li key=2> Some Model Y</li>
</ul>
like image 571
kumarmo2 Avatar asked Nov 17 '25 06:11

kumarmo2


1 Answers

React identifies elements with unique key prop. In a Component, if you think the list of elements will have overlapping ids you can always pass a unique key prop.

If the element you are rendering is relevant to make, pass in the key as

<div key={`make_${makeId}`} />

If the element you are rendering is relevant to model, pass in the key as

<div key={`model_${modelId}`} />
like image 151
Dinesh Pandiyan Avatar answered Nov 19 '25 20:11

Dinesh Pandiyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!