DEV Community

Cover image for react arrayMap utils
yathink3
yathink3

Posted on • Updated on

react arrayMap utils

Hello React developers,

I created a utility function called reactMap and arrMap. You can make use of it. Please find the attached code below

import React from 'react';

export function reactMap(arr, ifFn, elseFn) {
  if (!arr || !Array.isArray(arr) || arr.length === 0) {
    if (elseFn) {
      if (typeof elseFn === 'function') return elseFn();
      else return elseFn;
    } else return false;
  } else {
    if (ifFn) {
      if (typeof ifFn === 'function') {
        return React.Children.toArray(arr.map(ifFn));
      } else return React.Children.toArray(arr.map(() => ifFn));
    } else if (elseFn) return false;
    else return true;
  }
}

export function arrMap(arr, ifFn, elseFn) {
  if (!arr || !Array.isArray(arr) || arr.length === 0) {
    if (elseFn) {
      if (typeof elseFn === 'function') {
        const result = elseFn();
        if (result && Array.isArray(result)) return result;
      } else {
        if (elseFn && Array.isArray(elseFn)) return elseFn;
      }
    }
  } else {
    if (ifFn) {
      if (typeof ifFn === 'function') {
        return arr.reduce((acc, item, i) => {
          const value = ifFn(item, i, arr);
          if (value === false || value === undefined) return acc;
          else return [...acc, value];
        }, []);
      } else return arr.map(() => ifFn);
    } else if (!elseFn) return arr;
  }
  return [];
}

Enter fullscreen mode Exit fullscreen mode

Below is the snippet for you to know the way to use it, and also the new structure you can use replacing with the old structure.

this is old structure

const arr = [1,2,3,4,5];

{arr && Array.isArray(arr) && arr.map(val=>
    <div key={val}>{val}</div>
)}

{arr && Array.isArray(arr) && arr.length===0 &&
    <div>No data to show</div>
}

{arr && Array.isArray(arr) && arr.length!==0 &&
    <div>arr has content</div>
}

Enter fullscreen mode Exit fullscreen mode

this is new structure

import { reactMap } from 'utils/reactMapUtils';

const arr = [1,2,3,4,5];

{reactMap(arr, val => <div>{val}</div>, <div>No data to show</div>)}

{reactMap(arr) && <div>arr has content</div>}

Enter fullscreen mode Exit fullscreen mode

by using the above structure, we have the advantages that are listed below.

  1. No more null check is required.
  2. We don't have to pass the key prop anymore.
  3. We don't have to to write array empty condition seperatly anymore too.
  4. Don't have to check whether the arr contains data or no.

arrMap functionality similar to reactMap but arrMap always returns an array. it is useful when we want to manipulate array contents

Top comments (0)