Variable in event of react list component

Here is my code:

export default function App() {
  const array = ["item1", "item2", "item3"];
  let progress = "";
  const list = array.map((item) => {
    progress += `/${item}`;
    return (
      <input
        key={item}
        type="button"
        value={item}
        onClick={() => {
          console.log(progress);
        }}
      />
    );
  });
  return <div className="App">{list}</div>;
}

Also, you can try it on sandbox

When I click item1 button on the page. Why the console log /item1/item2/item3?

The expected behavior is that:

When item1 button is clicked. Console log /item1;

When item2 button is clicked. Console log /item1/item2;

Thanks.

Answer

When you click the button, the arrow function you provided will fire. This means that the function will read the variable only when the arrow function is being called. And since the progress variable isn’t being created inside the mapping or arrow function, but rather outside it, the last mapped input element will set it to item1item2item3, meaning it will be the same when you click each of the inputs.

To fix this, you could assign a local variable to be equal to progress inside the map method, like so:

export default function App() {
  const array = ["item1", "item2", "item3"];

  let progress = "";

  const list = array.map((item) => {
    progress += item;
    let local = progress;
    return (
      <input
        key={item}
        type="button"
        value={item}
        onClick={() => {
          console.log(local);
        }}
      />
    );
  });
  return <div className="App">{list}</div>;
}

I haven’t tested this exactly, but it should work.

Leave a Reply

Your email address will not be published. Required fields are marked *