12

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.

2
  • 4
    IIRC key is a property, so I think something like React.createElement(children[i], {key: i}) might work. Commented Apr 29, 2019 at 19:01
  • That did the trick. Thank you zzzzBov Commented Apr 29, 2019 at 19:09

2 Answers 2

24

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

Sign up to request clarification or add additional context in comments.

2 Comments

👍 for the writeup.
Works as a charm
0

  const tag = "div";
  const key = "myDiv";
  const className ="your class Name";
  const your childrenOrText = "thisCaseisTextOnly";

  const theTag = createElement(tag, { key: key, className }, childrenOrText );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.