1

Using React I am trying to map an array of elements into a containing HTML element.

However I can not figure out how to map two elements into one HTML element since these elements will have to be closed.

This is an example of what I would like to do. Map two components inside a containing element of className="row" but I can not because the JSX elements have to be closed:

const CalendarGrid = (events) => {
  let content = [];
  events.events.map((event, index) =>{

    if (index % 2 != 0) {
        content.push(
          <div className="row">   
          <EventCardRight key={event.id} event={event} align="right"/>
        )
      }if (index % 2 == 0)
      {
          content.push(
            <EventCardLeft key={event.id} event={event} />
            </div className="row">   
          );
      }

  });
  return (
    <div>
        {content}
    </div>
  );
}
dwigt
  • 591
  • 1
  • 6
  • 18

2 Answers2

1

You can take advantage of inline logical operators and map through events directly as:

const CalendarGrid = (events) => {
  return (
    <div>
      {events.events.map((event, index) => 
        <div key={event.id} className="row">
          {index % 2 != 0 ? (
            <EventCardRight key={event.id} event={event} align="right"/>
          ) : (
            <EventCardLeft key={event.id} event={event} />
          )}
        </div>
      )}
    </div>
  )
}
mersocarlin
  • 7,214
  • 1
  • 25
  • 38
1

First, I would split your array to chunks of size 2. See How to split a long array into smaller arrays, with JavaScript, I will use lodash for that:

const rows = _.chunk(events.events, 2);

now I can simply map every row to elements:

const content = rows.map((rowEvents, index) => (
   <div key={index} className="row">
      <EventCardRight event={rowEvents[0]} align="right" />
      <EventCardLeft event={rowEvents[1]} />
   </div>
));
Sulthan
  • 123,697
  • 21
  • 207
  • 260