zbeedatm
zbeedatm

Reputation: 679

How to render a map in React?

I want to display list of items (projects) grouped by month-year...

For grouping I did the following and printed the results which seems fine:

// this gives an object with dates as keys
    const groups = filteredProjects.reduce((groups, project) => {
        //const date = project.Properties.ModificationTime.Value.split('T')[0];
        //const  month = moment(project.Properties.ModificationTime.Value, 'YYYY-MM-DD').format('MMM');
        const  date = moment(project.Properties.ModificationTime.Value, 'YYYY-MM-DD').format('MMM-YYYY');
        if (!groups[date]) {
            groups[date] = [];
        }
        groups[date].push(project);
        return groups;
    }, {});

    // Edit: to add it in the array format instead
    const groupedProjects = Object.keys(groups).map((date) => {
        return {
            date,
            projects: groups[date]
        };
    });

Now I want to render it in a way that each month will have it's own projects components. So I tried the following:

 {groupedProjects.map((date, arr) => (
                    <div className="inline">
                        {date}
                        {arr.map((item) =>
                            <Project
                                key={item.Name}
                                project={item}
                            />
                        )}
                    </div>
                    ))}

But it's not working. How can I render a map in such a way?

Upvotes: 0

Views: 71

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

You should use map on groupedProjects array like this,

{groupedProjects.map(({date, projects}) => (
      <div className="inline">
         {date}
         {projects.map((item) =>
             <Project
                key={item.Name}
                project={item}
             />
         )}
       </div>
))}

Upvotes: 0

vatz88
vatz88

Reputation: 2452

I think your syntax for using Array.map is wrong. Read more about the syntax on mdn

Try this, I'm destructing the object of groupedProjects in the map callback function to get the value of date and projects as arr

{groupedProjects.map(({date, projects: arr}) => (
      <div className="inline">
                    {date}
                    {arr.map((item) =>
                        <Project
                            key={item.Name}
                            project={item}
                        />
                    )}
                </div>
                ))}

Upvotes: 2

Related Questions