Suomi Suomi - 3 months ago 14
React JSX Question

How to loop through an array in componentDidMount()?

I'm learning more ReactJS, and trying to display data from my example API.

I'm able to display one title, but I can't figure out how to loop through the array, and display all the titles?

Currently I can display one event title, e.g. "Event1", but I would like to display, e.g.

Event1
Event2
Event3
...


Here is my app.js:

class App extends React.Component {

constructor(props) {
super(props);
this.state = {
title: ''
}
}

componentDidMount() {
var th = this;
this.serverRequest =
axios.get(this.props.source)
.then(function(event) {
th.setState({
title: event.data[0].title[0].value
});
})
}

componentWillUnmount() {
this.serverRequest.abort();
}

render() {
return (
<div>
<h1>Here you can see one event title:</h1>
<h2>{this.state.title}</h2>
</div>
);
}
}

ReactDOM.render(
<App source="http://localhost:8888/my/api/events" />,
document.getElementById('container')
);


And here is my index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>

<div id="container"></div>

<script src="https://npmcdn.com/react@15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom@15.3.1/dist/react-dom.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<script type="text/babel" src="js/app.js"></script>

</body>
</html>


Here is a console.log() of the data I get from my API:

enter image description here

How could I loop through the array, to display all the titles, and not just one? With map(), or adding a for loop in componentDidMount()?

Answer

Change axios.get to store all the data you received from server in this.state.data:

axios.get(this.props.source)
     .then(function(event) {    
          th.setState({
            data: event.data
          });
      })

Iterate through it:

render() {
    var titles = []
    this.state.data.forEach(item => {
       titles.push(<h2>{item.title[0].value}</h2>)
    })
    return (
      <div>
        <h1>Here you can see all titles :)</h1>
        {titles}
      </div>
    );
}

or

render() {
    return (
      <div>
        <h1>Here you can see all titles :)</h1>
        {this.state.data.map(function(item){
           return <h2>{item.title[0].value}</h2>
         })}
      </div>
    );
}