Home > Software engineering >  Unable to dinamically create elements in a loop using React Native
Unable to dinamically create elements in a loop using React Native

Time:09-21

I´m trying to dinamically create some elements based on a list of JSON objects like this:

{Object.entries(this.state.topTen).forEach(([name]) => {
    console.log(name); // this correctly print the list of names
    React.createElement(MyCustomComponent, {name: name});
})}

I also tried the following approach inside the loop:

<MyCustomComponentname={name} />

But I don´t see anything rendered in the screen, I know for sure that this.state.topTen has the correct information because the console.log inside the loop is displaying the correct information. And if I add a <MyCustomComponentname={name} /> outside of the loop, the component is rendered correctly.

CodePudding user response:

The method .forEach() will not return anything. You will need to use the .map() method of the array and return the result of React.createElement(MyCustomComponent, {name: name});.

For example:

{Object.entries(this.state.topTen).map(([name]) => {
    console.log(name); // this correctly print the list of names
    return React.createElement(MyCustomComponent, {name: name});
})}

Using .map() will return an array with whatever items you have returned within the callback. This resulting array can be rendered with React because the callback is returning the result of React.createElement(...).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

CodePudding user response:

I completely agree with the answer suggested by Bradon also it's better to pass the key prop from the array to the child component which will increase the performance of the app while re-rendering and also can eliminate unexpected issues. https://reactjs.org/docs/lists-and-keys.html go through the link for more clarity.

  • Related