0

I am using map to loop over the array object getting from server, each object is used for one row in a table to show data. And I want to do a particular action for each row by calling function and pass to an index. The code here:

       <TableBody>
          {productsData.map((product, index) => {
            return (
              <TableRow key={product.productId}>
                <TableCell>
                  <Button
                    aria-owns={anchorEl ? `manipulation${index}` : undefined}
                    aria-haspopup="true"
                    onClick={handleClick}
                    className={classes.button}
                    size="small"
                    variant="contained"
                  >
                    Thao tác
                  </Button>
                  <Menu id={`manipulation${index}`} anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleClose}>
                    <MenuItem onClick={**handleOpen(index)**}>Xem trước</MenuItem>
                  </Menu>
                </TableCell>
              </TableRow>
             )
           })}
        </TableBody>

The way I declare handleOpen: const handleOpen = (index) => () => {...} => I expected the handleOpen will render like that: handleOpen(0) for row 0, handleOpen(1) for row 1. But it's always end up with the last index of array. May be about the closure in javascript but I dont know how to fix

Please give me any suggestion. Thank in advance.

Minh Kha
  • 1,052
  • 8
  • 13

1 Answers1

1

The way you've done it will call the handleOpen function immediately after rendering, instead of only calling it on click like you want it to.

To fix this, use an anonymous function:

<MenuItem onClick={() => handleOpen(index)}>

This will create a function that will only be called on actual click of the MenuItem component.

bamtheboozle
  • 5,847
  • 2
  • 17
  • 31
  • Sorry I forget to mention how I defined handleOpen function. – Minh Kha May 15 '19 at 13:56
  • const handleOpen = index => () => {..}. It's the same to your way bro. – Minh Kha May 15 '19 at 13:57
  • It's not, because your way you're just overwriting the handleOpen function with the last index always, so on each click you're calling the function constructed with the last index. – bamtheboozle May 15 '19 at 14:00
  • I tried your way but still get stuck. It's weird. I used to face to the same situation, with my way, it works just fine, but now I really dont know what happen – Minh Kha May 15 '19 at 14:07
  • It is the same, his handleOpen is returning a function that returns a function, that will have index captured. So it should work. I suggest the OP creates a simple snippet / codebin etc... – Keith May 15 '19 at 14:10
  • I noticed that, when I moved handleOpen function up to the parent is Button, it works. But the child is not – Minh Kha May 15 '19 at 14:57