Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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' }
]

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try a conditional append.

const extendedTabs = [...modalTabs, ...(gradeIsMandatory ? [{ key: 'grade', title: 'Grade' }] : [] )];
about 4 years ago · Juan Pablo Isaza Relatório

0

You cannot skip a map iteration. You can however just return <Fragment /> if your map condition isn't met.

about 4 years ago · Juan Pablo Isaza Relatório

0

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 {
    ...
  }
};
  1. send the gradeIsMandatory as a property to this component
  2. define modalTabs as state
  3. use a useEffect hook with props.gradeIsMandatory as a dependency
  4. 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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda