I have data coming from an external API that I am trying to display in a table. The data comes back with date time stamps.
I'd like to render the data in a table, but with an extra row in that displays the date when the date changes.
What I've tried
- I've attempted updating a lastDate prop value.
- I've attempted conditional rendering with the (condition) ? expected : other syntax and a variable in the render() method.
- I can't figure out how to keep track of the current date variable and update it on every loop iteration.
- I've tried splitting the DateRow and the DataRow into seperate components and passing the date, but the state is not persisted.
- I'm not sure what is best practice for doing this. Or if it's just a bad idea.
import React from 'react';
import { Link } from 'react-router-dom';
import { Table } from 'react-bootstrap';
import * as helpers from '../../common/helpers';
export default class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(`https://api.example.com`)
.then(res => res.json())
.then(
(result) => {
this.setState({
data: result
});
}
)
}
render() {
const { data } = this.state;
return (
<>
<h4>Most Recent</h4>
<Table>
<thead>
<tr>
<th>Time</th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
{data.map(newRow => (
// Here I'd like to conditionally render a row if there has been a change in day from the last row before rendering the next row.
// ie. if previousDate != currentDate
// <tr>
// <td>{helpers.getFormattedDate(newRow.time)}</td>
// <td></td>
// <td></td>
// </tr>
// Then render the following :
<tr key={newRow.id}>
<td>
{helpers.getFormattedTime(newRow.time)}
</td>
<td>
<Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
</td>
<td>
{/* Some more content here */}
</td>
</tr>
))}
</tbody>
</Table>
</>
);
}
}
Any help here would be appreciated, I'm more than a bit lost on this one.
Thanks!