I have a React component that will render a table based on data from an Ajax call. There might just be one row of data, or there might be a maximum of N rows(not a huge amount, but there's a limit).
Using react-bootstrap
, how would I create a table depending on the data I get from this.state.data
?
Here's some sample code from render
of the class. How would I populate the individual cells depending on the length of my array?
The array contains an object for each row I wish to populate, with data corrosponding to Name
and Address
as well as Age
(just an example). How do I populate the <td>
's with the right amount? It might be anywhere from 1 to N.
render : function () {
let personArray = []; // Array containing objects that each match the three columns I wish to populate.
for(let i = 0; i < personArray.length; i++){
console.log(personArray[i]); // Prints correctly each object with three value key pairs inside
}
const popoverLeft = (
<Popover id="popover-positioned-left" title="Country name">
<Table striped bordered condensed hover>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
// Goes on ..
</tr>
<tr>
<td></td>
<td></td>
<td></td>
// Goes on ..
</tr>
<tr>
<td></td>
<td></td>
<td></td>
// Goes on ..
</tr>
</tbody>
</Table>
</Popover>
);
return(
<div>
<OverlayTrigger trigger="click" placement="right" overlay={popoverLeft}>
<div>
</div>
</OverlayTrigger>
</div>
)
You can do something like this :
In your render :
<Table striped condensed hover>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Address</th>
<th>Age</th>
</tr>
</thead>
<tbody>
{personArray.map(this.renderPerson)}
</tbody>
</Table>
Your renderPerson function :
renderPerson(person, index) {
return (
<tr key={index}>
<td>{person.name}</td>
<td>{person.address}</td>
<td>{person.age}</td>
</tr>
)
}
The map function will iterate over your array and return a new array of elements to render.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With