'React.js/React-Native how to skip Map() iteration if condition is falsy?
I have this simple component in React-Native, My goal is to skip the iteration if the given argument gradeIsMandatory is false, it should only iterate over warranty and price, How can I achieve this result without affecting performance? I will take any advice thanks
import React, { useCallback } from 'react';
import { View, Text, SafeAreaView, SectionList, StyleSheet, Image, TouchableOpacity, Alert} from 'react-native';
export const ModalHeader: React.FC<{}> = () => {
const gradeIsMandatory = false
//code I tried to use
useEffect(()=>{
if(!gradeIsMandatory){
let appendGrade = { key: 'grade', title: 'Grade' }
modalTabs.push(appendGrade)
}
},[])
return (
<View>
<View>
<View>
{modalTabs.map((tab, i) => (
<TouchableOpacity>
<Text>{tab.title}</Text>
</TouchableOpacity>
))}
</View>
</View>
</View>
);
}
const modalTabs = [
{ key: 'warranty', title: 'Your Waranty' },
{ key: 'price', title: 'Your price' }
]
Solution 1:[1]
I would delete the useEffect and render this:
return (
<View>
<View>
<View>
{modalTabs.map((tab, i) => (
<TouchableOpacity>
<Text>{tab.title}</Text>
</TouchableOpacity>
))}
{
gradeIsMandatory && <TouchableOpacity><Text>Grade</Text></TouchableOpacity>
}
</View>
</View>
</View>
);
Solution 2:[2]
You cannot skip a map iteration. You can however just return <Fragment /> if your map condition isn't met.
Solution 3:[3]
this useEffect will run once just after the first render of the component, manipulating modalTabs there will do nothing becuase modalTabs is not a State of this component. the correct way is:
import { useState, useEffect } from "react";
const modalTabsInitialValue = [
{ key: "warranty", title: "Your Waranty" },
{ key: "price", title: "Your price" }
];
export default (props) => {
const [modalTabs, setModalTabs] = useState(modalTabsInitialValue);
useEffect(() => {
if (props.gradeIsMandatory) {
setModalTabs((prevModalTabs) => {
const appendGrade = { key: "grade", title: "Grade" };
return [...prevModalTabs, appendGrade];
});
}
}, [props.gradeIsMandatory, setModalTabs]);
return {
...
}
};
- send the gradeIsMandatory as a property to this component
- define modalTabs as state
- use a useEffect hook with props.gradeIsMandatory as a dependency
- inside the useEffect based on the value of gradeIsMandatory create a new array and change the modalTabs state forcing the component to reRender
Update: this is not the best solution for this problem, the correct answer as windowsill said is a simple const: answer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | shlomieb |
| Solution 2 | chromaloop |
| Solution 3 |
