Suomi Suomi - 1 month ago 10
React JSX Question

In React, how to show data from API in a HTML table?

I'm trying to display data from my example API. At the moment I'm able to loop through the array, and display all the titles, for example:

EventTitle1
EventTitle2
EventTitle3
...


Here is my code:



class App extends React.Component {
constructor() {
super();
this.state = {
data: []
}
}

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

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

render() {
var titles = []
this.state.data.forEach(item => {
titles.push(<h3 className=”events”>{item.title[0].value}</h3> );
})
return (
<div className=”container”>
<div className=”row”>
<div className=”col-md-6 col-md-offset-5">
<h1 className=”title”>All Events</h1>
{titles}
</div>
</div>
</div>
);
}
}

ReactDOM.render(
<App source=”http://localhost:8888/example/api/events" />,
document.getElementById(‘container’)
);





How could I create an HTML table, to display only the five latest event titles from the API (and later other data) inside the table?

For example:

return (
<table>
<tr>
<th>Event title</th>
<th>Event location</th>
</tr>
<tr>
<td>First event title {titles[0]} ?? </td>
<td>San Fran</td>
</tr>
<tr>
<td>Second event title {titles[1]} ??</td>
<td>London</td>
</tr>
</table>
);

Answer

Create an array of<tr> and add it into the table.

class App extends React.Component {
constructor() {
   super();
   this.state = {
      data: []
   }
}
 
componentDidMount() {
 var th = this;
 this.serverRequest = axios.get(this.props.source)
 .then(function(event) { 
     th.setState({
         data: event.data
     });
 })
}

componentWillUnmount() {
  this.serverRequest.abort();
}
 
render() {
 const contents = this.state.data.forEach(item => {
      //change the title and location key based on your API
      return <tr>
        <td>{item.title}</td> 
        <td>{item.location}</td>
      </tr>
 })
 return (
    <div className=”container”>
      <div className=”row”>
         <div className=”col-md-6 col-md-offset-5">
             <h1 className=”title”>All Events</h1>
             <table>
              <tr>
                <th>Event title</th>
                <th>Event location</th> 
              </tr>
                {contents}
            </table>
         </div>
      </div>
    </div>
  );
 } 
}

ReactDOM.render(
   <App source=”http://localhost:8888/example/api/events" />, 
   document.getElementById(‘container’)
);