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

134
Views
react onchange push values to objects

I have an dynamic created fields (input tag)

const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data

{navtive?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />
...
{rolls?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />

Expected Output:

const output = {
    native: [{id: 1, fee: "12"}, {id: 5, fee: "2"}],
    rolls: [{id: 4, fee: "1332"}],
};

onChange function :

const handleChange = (field, value, index) => {
    setData((prevState) => {
        const nextState = [...prevState];
        nextState[index][field] = value;
        return nextState;
    });
};

How to get the expected output ? What am I making wrong in the onChange function.

Thank you

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

0

You must add more arguments to handleChange for this output. type - to understand what property is native or rolls. id - id from current data element. Example - sandbox

const handleChange = (type, field, value, index, id) => {
    setData((prevState) => {
      const nextState = [...prevState[type]];
      nextState[index] = {
        ...prevState[type][index],
        id,
        [field]: value
      };
      return {
        ...prevState,
        [type]: nextState
      };
    });
  };

JSX

handleChange("native", "free", e.target.value, index, item.id)
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!