React Warning: Flattenchildren(...): Encountered Two Children With The Same Key
Solution 1:
It is not a good idea to use the index as the key. A key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true. From: https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
It is much better to use a unique string from each item you are mapping over as the key. Something like <option key={value.id}>
or if a key does not exist, create a unique identifier by doing something like <option key={value.name + value.description}>
.
Solution 2:
Adding the index as value fixed this. Thanks @azium for your sugegstion.
<select id="product" name="Product" value={this.props.product} onChange={this.changeOption.bind(this, 'product')}>
<optionvalue=''>Product</option>
{this.props.productOptions.map(function(option, value) {
return (<optionkey={value}value={option}>{option}</option>)
})}
</select>
Solution 3:
I'm a big fan of using key by combining index with some constant value rather than using key={value.name + value.description}
:
key={'some-constant-value'+index}
This is because I can pass the key knowingly which compoent is it for. For eg. <ComponentA key={'compoent-a-'+i} />
. Also, I follow this approach is because simple html convention matches like we give id="my-some-of-the-id"
or something.
So, even if you want to use name and description as the key, you may use like this rather:
key={'some-constant-'+value.name+'-'+value.description}
This is just an opinion. Though, I follow html convention when writing props value.
Solution 4:
actually you need to specify to each children a unique key,so for that you need to create another key,for example if you are getting data from the database so for that create a new column for example (id) and then add value of that column to your div or what matter you are looping on as a key
varFilterOptions = React.createClass({
changeOption: function(type, e) {
var val = e.target.value;
this.props.changeOption(val, type);
},
render: function() {
return (
<divclassName="filter-options"><divclassName="filter-option"><selectid="product"name="Product"value={this.props.product}onChange={this.changeOption.bind(this, 'product')}><optionvalue=''>Product</option>
{this.props.productOptions && this.props.productOptions.map(function(option) {
return (<optionkey={option.id}value={option}>{option}</option>)
})}
</select></div></div>
);
}
});
i hope this help anyone in the future.
Post a Comment for "React Warning: Flattenchildren(...): Encountered Two Children With The Same Key"