H
H
Herberito Galustyan2019-08-06 16:34:45
React
Herberito Galustyan, 2019-08-06 16:34:45

How to make a map in React?

I want to display a list of subjects (projects) grouped by month and year...
For grouping, I did the following and printed the results, which seem to be good:

// 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 make it so that each month has its own project 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 doesn't work. How can I make a map this way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Petr Muhurov, 2019-08-06
@Herberto

doesn't work because

const groupedProjects = Object.keys(groups).map((date) => {
        return {
            date,
            projects: groups[date]
        };
    });

you have objects in the array, and here
groupedProjects.map((date, arr) => (
                    <div className="inline">
                        {date}
                        {arr.map((item) =>
                            <Project
                                key={item.Name}
                                project={item}
                            />
                        )}
                    </div>
                    ))}

you are trying to render an object and underneath it is a Number.map
groupedProjects.map(({ date, projects }) => (
  {date}
  {projects.map()}
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question