Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React create element with key

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.

like image 673
eagercoder Avatar asked Apr 29 '19 18:04

eagercoder


1 Answers

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});
    });
  }

like image 102
Gaʀʀʏ Avatar answered Sep 18 '22 22:09

Gaʀʀʏ