how to use Keys in React Dynamic children the right way

Recently I was stuck in a react component which children components doesn’t update no matter how I set the state or props. I eventually find the solution is really easy and simple: set the Key value unique across the parent context all the time.

Problem:

The issue can happen in all cascade drop down scenarios. For example, the parent dropdown is a list of countries, and the child dropdown is a list of cities. If the country drop down list changes, the cities drop down should reload with the corresponding country’s cities. However once the cities drop down option changed, it will always keep  the current selected status when I change the countries drop down.

Solution:

The solution is pretty simple: always make sure the Key value in the child list unique across the countries, not just the current selection.

Case study:

My previous thought was that just make the the Key value unique, and the simplest way is just pass the index of the child children array, and it works in most cases, as long as you don’t have a cascade dropdown. and it is true in that case. However in the cascade drop down scenario, the index is not unique across parent drop down selection, which means the child index 1 of city New York in the drop down for United State, is not the same for London for United Kingdom. If the index of the array is still passed to child dynamic list, it will cause the child component think it’s the same component as its previous one, so just leave it and don’t update the child component. In my scenario, I just need to pass the id of country and id of city as the Key value, and it fix the problem.

Lesson Learnt:

  1. React can only determine child dynamic component based on the Key
  2. always make sure the Key is unique across the parent component, not the current selection
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s