G\'Day. I want to iterate over a bunch of JSON objects and turn them into React Elements. The objects look like this
\"field
You need to add a unique key prop to your React element.
According to the React docs:
Keys
help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort
You can do it like
for (var fieldIn in fieldsIn) { // array of FORM ELEMENT descriptions in JSON
console.log(fieldIn);
let field = React.createElement(SmartRender, // go build the React Element
{key: fieldsIn[fieldIn].key, fieldIn},
null); // lowest level, no children, data is in props
console.log('doin fields inside');
fieldsOut.push(field);
}
Why are keys necessary?
By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.
For example, when adding an element at the end of the children, converting between these two trees works well:
- first
- second
- first
- second
- third
React will match the two
trees, match the two
trees, and then insert the
tree.
If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly.
- first
- second
- third
- first
- second
That is where keys come in handy.