Is There a Shorter Way to Render This Code?

Viewed 27

I am trying to render input data from a .json into a container for a to-do list on React. I have the days displayed on the container, but the code below is for individual days. So far, I just copied + pasted this seven times and changed the days.

            <h4 className="day">Monday:</h4>          
            {renderTasks.map((time) => {
                if (time.day === 'Monday') {return (
                <div className="taskBox" key={time.id}>
                    <span className="renderTime">
                        {time.hour}:{time.minute}{time.time}</span>
                    <span className="renderTask">{time.task}</span>
                </div>)}
            })
        }

I'd like to know if there's a convenient way to extract data and render them underneath a specific day on React? (eg: if time.day !== '' display data underneath this day) I really appreciate the help. I've been learning React for a bit.

1 Answers

You could have an array of weekdays, and the iterate through it to render each individually. Something like this:

declare the list

const weekdays =['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

render

{weekdays.map(weekday =>(
<>
<h4 className="day">{weekday}:</h4>          
            {renderTasks.filter(time=>time.day===weekday).map((time) => {
                return (
                <div className="taskBox" key={time.id}>
                    <span className="renderTime">
                        {time.hour}:{time.minute}{time.time}</span>
                    <span className="renderTask">{time.task}</span>
                </div>)
            })
</>)
Related