Home > Back-end >  i cant access index of map function within function call on button(onClick()), which is within scope
i cant access index of map function within function call on button(onClick()), which is within scope

Time:11-08

Initial State

const [variation, setVariation] = useState([
    {
      name: "",
      value: [""],
    },
  ]);

function on button click

const addValueField = (e, index) => {
    e.preventDefault();
    const field = [...variation];
    field[index].value.push("");
    setVariation(field);
  };

html render:

<div>
 {variation.map((value, index) => {
        return (
          <div className="form-control">
            <input
              key={index}
              className="bg-base-200 m-1 shadow appearance-none border rounded text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
              type="text"
              placeholder="Enter Variation Type"
            />
            <div className="form-control">
              {variation[index].value.map((value, i) => {
                return (
                  <input
                    type="text"
                    key={i}
                    className="bg-base-200 m-1 shadow appearance-none border rounded text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    placeholder="Enter Value"
                  />
                );
              })}
              <button onClick={(e, index) => addValueField(e, index)}>
                Add another value
              </button>
            </div>
          </div>
        );
      })}
</div>

When addValueField(e,index) is called on button click, it does not pick the index of parent map(), but button is within parent map() scope, so it does not pass index to the function and error is generated.

CodePudding user response:

onClick doesn't give you the index. You have to get the index from the map directly if you use as

<button onClick={(e) => addValueField(e, index)}>
  Add another value
</button>;

and you can set variation state as

const addValueField = (e, index) => {
  e.preventDefault();
  setVariation((state) =>
    state.map((o, i) => (i === index ? { ...o, value: [...o.value, ""] } : o))
  );
};
  • Related