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>
);
I just would not code it in the above examples like that.
this
reminds me the old days of angularjs which a lot of people didvar vm = this
(vm for view model )Need to be using modern javascript with arrow functions and use
map
and notforEach
You can simply use the
slice
operator to get the first 5 elements of you array, and then directly usemap
.There is also no need to use a
titles
array, you can just put the snippet inline in the jsx.The important part of the code is:
Here is the full example:
Create an array of
<tr>
and add it into the table.