Sankit Acharya Sankit Acharya - 2 months ago 10
React JSX Question

You may have returned undefined, an array or some other invalid object rendering state data

Have been facing issue while iterating through a list and printing elements in React.

The React Code is:

import React from 'react';
import ReactDOM from 'react-dom';

class NewComponent extends React.Component {
constructor(props){
super(props);
this.state = {myData: []}
}

componentWillMount(){
let data = document.getElementById('demo').innerHTML;
data = JSON.parse(data);
this.setState({myData: data});
}

render() {
return this.state.myData.map((item) => {
return (
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
);
});
}
}


ReactDOM.render(
<NewComponent />,
document.getElementById('demo')
)


And I'm getting an error of:

bundle.js:830 Uncaught Error: NewComponent.render(): A valid React element
(or null) must be returned. You may have returned undefined, an array or
some other invalid object.


I'm pretty sure there is some issue with returns in the render function of the
Not sure what is the issue though.

EDITS

I have made the following edits, the error is not there anymore but nothing is rendering.

renderList() {
console.log("Running");
return this.state.myData.map((item) => {
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
});
}

render() {
console.log(this.state.myData);
if(this.state.myData.length)
return <div>{this.renderList()}</div>
else
return <div>Loading...</div>
}


In Chrome console I'm getting:

(2) [{…}, {…}]
0:{_id: {…}, description: "hello", title: "sankit"}
1:{_id: {…}, description: "lets add some thing new", title: "hi"}
length:2
_proto_:Array(0)

Running

Answer Source

what you can do is extract your js code from the render method in a separate method like so:

renderList() {
   return this.state.myData.map((item) => {
      <div>
       <h3>{item.title}</h3>
       <p>{item.description}</p>
      </div>
   })
}

then in your render method:

render() {
  if(this.state.myData.length){
    return (
       <div>{this.renderList()}</div>
    );
  }
  else
  {
    return (
      <div>Loading...</div>
    );
  }
}