Search code examples
javascriptreactjsmap-function

Render components based on the data from a multidimensional array in React


I have an array with items which can have even or odd number of items. I made a function which puts each two elements in their own array inside a main array, so it looks like this at the end;

items array: [{}, {}, {}, {}]
returned array: [[{}, {}], [{}, {}]]

items array: [{}, {}, {}]
returned array: [[{}, {}], [{}, undefined]]

I did this because I want to render each Bootstrap row with two columns on the page. Now, I'm not sure how to implement mapping through this array. To a certain extent I know how to do this;

  1. Map through returned array.
  2. If second element in current array is undefined return a row with just one item.
  3. If both elements are defined in current array return a row with both items.

But by React rules I need to add additional key attributes to the elements I return with map so I would need to somehow keep the track of index variable. What would be the efficient way to do this?


Solution

  • I can't think of a nice way to map your original array, but you could use a for loop and increment by 2 each iteration and just check if the second element is truthy before using it.

    Example

    class App extends React.Component {
      render() {
        const content = [];
    
        for (let i = 0; i < itemsArray.length; i += 2) {
          content.push(
            <div class="row" key={i}>
              <div class="col-md-6">
                <div class="option correct-option">{itemsArray[i].text}</div>
              </div>
              {itemsArray[i + 1] && (
                <div class="col-md-6">
                  <div class="option correct-option">{itemsArray[i + 1].text}</div>
                </div>
              )}
            </div>
          );
        }
    
        return <div>{content}</div>;
      }
    }
    

    If you want to use the array of arrays, you could map it and just check if the second element in the array is truthy before using it.

    Example

    class App extends React.Component {
      render() {
        return (
          <div>
            {itemsArray.map((items, index) => {
              <div class="row" key={index}>
                <div class="col-md-6">
                  <div class="option correct-option">{items[0].text}</div>
                </div>
                {items[1] && (
                  <div class="col-md-6">
                    <div class="option correct-option">{items[1].text}</div>
                  </div>
                )}
              </div>;
            })}
          </div>
        );
      }
    }