0

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.

fuzz
  • 195
  • 13
  • Couldn't you just map through the items array and display the `TimeHeader` and `ItemDisplay` for each item? – lpizzinidev Dec 07 '21 at 07:51
  • @LucaPizzini that is how I am doing it now, but I would like to show the TimeHeader only four times total. – fuzz Dec 07 '21 at 08:02
  • Finally figured it out after finding https://stackoverflow.com/questions/66231277/map-an-array-of-objects-but-only-displaying-unique-values – fuzz Dec 07 '21 at 10:32

0 Answers0