I'm attempting to render an array of react components without JSX with keys. The problem Unfortunately, I'm dealing with a JS error when i attempt to set the keys inside of my array:
Uncaught (in promise) TypeError: Cannot assign to read only property 'key' of object '#<Object>'
Here is the code:
import React, { Component } from 'react';
class Test extends Component {
mapChildObjects = () => {
const { children } = this.props;
let arr = [];
for (let i = 0; i < children.length; i++) {
arr.push(React.createElement(children[i]));
arr[i].key = i;
}
return arr;
}
render() {
return (
<div>
<div className={s.content}>
{this.mapChildObjects()}
</div>
</div>
);
}
}
export default Test
After reading the documentation: https://reactjs.org/docs/react-without-jsx.html, but was unable to find examples of adding keys inside of createElement
.
Note: this renders fine; the issue is not with the rendering of the component, but with the ability to add keys creating elements.
As zzzzBov mentioned in the comments, key
is a prop and can be passed inside an object as the second parameter of createElement.
Example
mapChildObjects = () => {
const { children } = this.props;
return children.map((child, i) => {
return React.createElement(child, {key: i});
});
}
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