Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
i cant access index of map function within function call on button(onClick()), which is within scope of map(),code is below

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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))
  );
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!