Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
React Native how to pass a function with a parameter inside a for-loop

I have the code below for a React Native app using Javascript and Im creating an array of objects that are data for a context menu.

When the user selects a project from the menu it should call handleSelectedProject which it does and pass the selected project object but I get undefined for the project variable.

Any ideas what the syntax should be to get the selected project object.

Thanks in advance.

export default MobileMenu = () => {
  const projects = useSelector(getPickerList);
  const [menuItems, setMenuItems] = useState([]);

  useEffect(() => {
    loadMenuItems();
  }, [projects]);

  const handleNewProject = () => {
    console.info("New Project");
  };

  const handleSelectedProject = (project) => {
    console.info("Project...", project);
  };

  const loadMenuItems = () => {
    let items = [];

    items.push({
      label: "New Project",
      onPress: handleNewProject,
      seperator: false,
    });

    items.push({ seperator: true });

    for (var i = 0; i < projects.length; i++) {
      items.push({
        label: projects[i].project_name,
        onPress: () => handleSelectedProject(projects[i]),
        seperator: false,
      });
    }

    setMenuItems(items);
  };

  return (
    <ScrollView>
      <View style={styles.container}>
        <ContextMenu items={menuItems} />
      </View>
    </ScrollView>
  );
};
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is with your for loop. The onPress callback will reference the loop variable when the loop is already finished, at which time i is out of range, so projects[i] will evaluate to undefined.

The easy solution is to use a block scoped variable i, so that projects[i] really references the variable that was created for that loop's iteration specifically. You do this by replacing var i with let i.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda