WebEngine WebEngine - 19 days ago 6
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) {
super(props);
this.state = {
children: []
};
}

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

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
key={this.props.id}
next of
id={this.props.id}
.

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

Answer

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