javascriptreactjsuse-statebuttongroup

Passing a value to a function within React map function


I've got an object

    const opt = [
  {
    name: "VAS",
    lines: ["."]
  },
  {
    name: "PACK",
    lines: ["1", "2"]
  },
  {
    name: "RET",
    lines: ["A"]
  }
];

And I'm trying to create a button group where all buttons are dynamically generated based on opt.name like this:

  <ButtonGroup
      color="primary"
      aria-label="large outlined primary button group"
    >
      {opt.map((elem, index) => (
        <Button onClick={changeState(elem.name)}>{elem.name} </Button>
      ))}
    </ButtonGroup>

The function itself sets the react state :

  const changeState = (x) => {
setValue(x);

};

For some reason this causes infinite re-render loop:

https://codesandbox.io/s/reverent-neumann-0t7qq?file=/src/App.js:292-391

The desired outcome is for the setValue to update the state based on button (opt.name ) I clicked on .

Thanks


Solution

  • You're invoking changeState immediately. Eg:

    <Button onClick={changeState(elem.name)}>{elem.name} </Button>
    

    is the same sort of thing as

    const clickHandler = changeState(elem.name);
    // ...
    return (
      <Button onClick={clickHandler}>{elem.name} </Button>
    );
    

    Change to:

      {opt.map((elem, index) => (
        <Button onClick={() => changeState(elem.name)}>{elem.name} </Button>
      ))}