Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!