WebEngine WebEngine - 1 month ago 11
React JSX Question

How to add key to React Component object

I'm trying to make tree style HTML. (with React)

This is Node class and It contains child nodes.

class Node extends React.Component {
constructor(props) {
this.state = {
children: []

render() {
return <div id={this.props.id} className="person">
<div className="info">
<div className="name">{this.props.name}</div>
<div className="childrenWrap">
<div className="children">

addChild(node) {
this.setState({children: this.state.children.concat(node)});


let tree = document.querySelector("#tree");
let root = ReactDom.render(<Person id="root" name="A" />, tree);
root.addChild(<Person id="child1" name="B" />);
root.addChild(<Person id="child2" name="C" />);
root.addChild(<Person id="child3" name="D" />);

but, this code will occur Warning 'Each child in an array or iterator should have a unique "key" prop.'.

So I add
next of

But It doesn't solved How can I solve this problem?


the problem is not with your parent component, but with your child components

this might solve the problem:

root.addChild(<Person id="child1" key="child1" name="B" />);
root.addChild(<Person id="child2" key="child2" name="C" />);
root.addChild(<Person id="child3" key="child3" name="D" />);

but in my opinion you are approaching the problem in a very bad way - you shouldn't keep whole rendered elements in your state, only the data needed to render them and then in render you should create the tree