An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
April 4, 2022 06:59 am GMT
Original Link: https://dev.to/yathink3/react-arraymap-utils-32ik
react arrayMap utils
Hello Frontend developers,
I created a utility function called reactMap. 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 [];}
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.
import { reactMap } from 'utils/reactMapUtils';const arr = [1,2,3,4,5];//you can replace the lines 4 to 9 with only one line, which is line 11. {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>}// --------------------------------------------------------------------------------------{reactMap(arr, val => <div>{val}</div>, <div>No data to show</div>)}//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.// Also, the lines 17 to 19 can be written as line 22{arr && Array.isArray(arr) && arr.length!==0 && <div>arr has content</div>}// ----------------------------------------------------------------------------------------{reactMap(arr) && <div>arr has content</div>}//Below are the advantages of the structure on the line 22 //1. No more null checks needed anymore.//3. Don't have to check whether the arr contains data or no.
Original Link: https://dev.to/yathink3/react-arraymap-utils-32ik
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To