Reputation: 87
I have a data store in state which needs to be displayed in a tabular format in UI using React. I am using a map function to display the data. I am able to display the data but the header is being displayed after each row as they are iterated in a loop.
Please let me know how can i display the output in tabular format with header being displayed only once?
return method code in React:-
return (
<div>
<br />
<input
type="submit"
class="btn btn-info btn-sm"
value="Create Itinerary"
onClick={this.callItinAPI}
/>
<br />
<br />
{this.state.ItinData.map((item) => (
<div>
<table id="DisplayRequest">
<tr>
<th>TripName</th>
<th>Booking ID</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
<tr>
<td>{item.Itinerary.TripName._text}</td>
<td>{item.Itinerary.Bookings.Booking.RecordLocator._text}</td>
<td>{item.Itinerary.StartDateLocal._text}</td>
<td>{item.Itinerary.EndDateLocal._text}</td>
</tr>
</table>
</div>
))}
</div>
);
Expected output:- Table header to displayed only once followed by all the data rows
Upvotes: 0
Views: 706
Reputation: 26258
The issue with your code is, you have put the table header in the loop itself which is wrong. Try something like this:
{
( this.state.ItinData.length > 0 ) // conditional rendering if data exist
?
<table id={'DisplayRequest'}>
<tr>
<th>TripName</th>
<th>Booking ID</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
// Use the map() function to iterate the array and display the table body here
{this.state.ItinData.map((item) => (
<tr>
<td>{item.Itinerary.TripName._text}</td>
<td>{item.Itinerary.Bookings.Booking.RecordLocator._text}</td>
<td>{item.Itinerary.StartDateLocal._text}</td>
<td>{item.Itinerary.EndDateLocal._text}</td>
</tr>
))}
</table>
null
}
Upvotes: 0
Reputation: 1448
You just need to extract the header from your loop :
<div>
{this.state.ItinData.length > 0 ? (
<table id={'DisplayRequest'}>
<tr>
<th>TripName</th>
<th>Booking ID</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
{this.state.ItinData.map((item) => (
<tr>
<td>{item.Itinerary.TripName._text}</td>
<td>{item.Itinerary.Bookings.Booking.RecordLocator._text}</td>
<td>{item.Itinerary.StartDateLocal._text}</td>
<td>{item.Itinerary.EndDateLocal._text}</td>
</tr>
))}
</table>;
) : null}
</div>
Upvotes: 1
Reputation: 1143
return (
<div>
<br />
<input
type="submit"
class="btn btn-info btn-sm"
value="Create Itinerary"
onClick={this.callItinAPI}
/>
<br />
<br />
<div>
<table id="DisplayRequest">
<tr>
<th>TripName</th>
<th>Booking ID</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
{this.state.ItinData.map((item) => (
<tr>
<td>{item.Itinerary.TripName._text}</td>
<td>{item.Itinerary.Bookings.Booking.RecordLocator._text}</td>
<td>{item.Itinerary.StartDateLocal._text}</td>
<td>{item.Itinerary.EndDateLocal._text}</td>
</tr>
))}
</table>
</div>
</div>
);
just move that td out side the loop
Upvotes: 0