I have an array with objects sorted with a date entry and a component to list in what approximated time it was listed.
const TimeHeader = ({date}) => {
const calculateDays = (date) => {
let timeDiff = new Date().getTime() - new Date(date).getTime();
let days = Math.ceil(timeDiff / (1000 * 3600 * 24));
return days;
}
let daysGone = calculateDays(date);
let color = "green";
let text = "Less than 1 Week";
if (daysGone > 7 && daysGone <= 30){
color = "blue";
text = "Less than 1 Month";
} else if (daysGone > 30 && daysGone <= 90){
color = "yellow";
text = "Less than 3 Months";
} else if (daysGone > 90){
color = "red";
text = "More than 3 Months";
}
return (
<div style={{backgroundColor: color}}>{text}</div>
)
}
How would I call upon this component to be rendered only once for each instance? (Once for Less than 1 week, once for less than one month etc)
Right now I am just calling it before each item listing but of course it leads a lot of repetition.
{list.map(item => {
return (
<div key={item.id}>
<TimeHeader date={item.date} />
<ItemDisplay item={item} />
</div>
)
})}
One solution would be to split the array to different categories beforehand, but I'm wondering if there is a nice solution that doesn't require splitting the array.