Home > Software engineering >  React Native how to pass a function with a parameter inside a for-loop
React Native how to pass a function with a parameter inside a for-loop

Time:05-25

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>
  );
};

CodePudding user response:

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.

  • Related