I'm getting the warning Each child in an array or iterator should have a unique "key" prop. Check the render method of Login
I want to pass an array of elements back, without using keys. I have to believe there's a workaround for this, without adding a pointless wrapper?
Note the
return [<div/>, <div/>];
render () {
return (
<div className='login'>
{this.mobileWeb()}
{this.pcWeb()}
</div>
);
}
mobileWeb () {
if (this.state.isMobileWeb === true) {
return [
<div className='sky-container'></div>,
<div className='sea-container'></div>
];
}
}
pcWeb () {
if (this.state.isMobileWeb !== true) {
return [
<div className='sky-container'></div>,
<div className='sea-container'>
<LoginForm onChange={this.onChange} ref='loginForm' onEmailChange={this.onEmailChange} onPasswordChange={this.onPasswordChange} />
<input type='submit' value='Submit' onClick={this.login} />
</div>
];
}
}
Keys help React identify which items have changed (added/removed/re-ordered). To give a unique identity to every element inside the array, a key is required.
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used to React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists.
To enable or disable items in the list box, enableItems method can be used. In the following example, the Bugatti Veyron Super Sport and SSC Ultimate Aero items are disabled by default and by clicking Enable Items buttons, the disabled items will be enabled.
Unstable keys can crash the whole app. Finally, we should note that keys need only be unique among adjacent elements or sibling list items. A key does not have to be globally unique, but only within the scope of a list.
There is a valid use case for not wanting to use keys, if you e.g. render strongly differing trees (think blog posts) or have a function that returns always the same array of items.
When you don’t provide an explicit key, React will use the index as key and emit a warning – however you would want to silence the warning, as using the index here is perfectly valid.
This doesn’t seem to be possible however, which has the sad consequence that you either have to make your code more complex for no reason (adding useless keys) or ignore the warnings (which means that valid warnings might be lost among the noise).
As of now, probably since 16.2.0 (November 28, 2017) you can wrap the elements inside <React.Fragment>
instead of an array. The child components do not need keys although array of Fragment
s will still need keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With