I'm getting this error 'Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of', When not adding the key in child component.
Why is this key necessary include here? because without this also component render correctly.
component - (parent)
import React, { Component } from 'react';
import ChildKey from './ChildKey';
import './App.css';
class ParentKey extends Component {
constructor() {
super();
this.state = {
keyList: [{
name: 'key1',
},{
name: 'key1',
},{
name: 'key1',
},{
name: 'key1'
}]
}
}
render() {
const {keyList} = this.state;
return (
<div style={{marginLeft: '40%'}}>
<h1>Parent Component</h1>
<br/>
<div>
{
keyList && keyList.map((data, index) => <ChildKey name={data.name} />)
}
</div>
</div>
)
}
}
export default ParentKey;
component (children) -
import React, {Component} from 'react';
export default class ChildKey extends Component {
constructor() {
super();
}
getStyle() {
return {
rootStyle: {
width: '40px',
height: '40px',
display: 'block'
}
}
}
render() {
const styles = this.getStyle();
return (
<div style={styles.rootStyle}>
<div>{this.props.name}</div>
</div>
)
}
}