0

I receive data from API, and display the data in row, each row will have a update button so that the function know which id to be updated.
Due to the reason I have many rows, it is not possible to setState or useRef for each row, is there any solution which I can obtain the user input for that certain id?
Example:

const data = [{id:1, number:0},{id:2, number:0},{id:3, number:0} ...] // a lot of data
const update=(id)=>{
   // get the new number of the id and call api to update only for the certain id
}

{data && data.map(x => {
                    return (
                        <div className={`row ${x.id}`} key={x.id}>
                            <div className='cell'>
                                {x.id}
                            </div>
                            <div className={`cell number`}>
                                {x.number}
                                <input className="cellInput" value={x.number} placeholder={x.number} />
                            </div>
                          
                            <div className='cell'>
                                <button onClick={(() => update(x.id))}>Update</button>
                            </div>
                        </div>
                    )
                })}
GG program
  • 127
  • 1
  • 1
  • 11

1 Answers1

0

You have to.

Basically you have only two choices: controlled components or uncontrolled components. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself. The following is an example for controlled components:

const [items, setItems] = useState([/* your data */]);
function handleChange(val, i) {
    const newItems = items.slice();
    newItems[i] = val;
    setItems(newItems);
}
return (
    <div>
        {items.map((val, i) => (
            <div key={i}>
                <input value={val} onChange={newVal => handleChange(newVal, i)} />
                <button onClick={() => {/* do something */}}>update</button>
            </div>
        ))}
    </div>
);