'React web app- unique inputs from a table of variable lengths

I am building an app to help me learn react and solidity. I have a table which lists available products on the site. I want customers to be able to input the number of items they would like to buy for each product (each row) separately.

It works if I make all of them change a single variable in my state but stylistically I would like each row to have a unique value. To solve this I created an array to hold each value ( the array is called inputs). The tough part here is that the number of products (rows in the table) can vary so I cant just hard code it.

Rendering the table:

 <tbody className="has-text-black-bis">
          {indices.map((a) => (
            <tr className="rows">
              <td ><strong>{this.state.itemNames[a]}</strong></td>
              <td ><strong>{this.state.costs[a]} Wei</strong></td>
              <td ><strong>{this.state.quantities[a]}</strong></td>
//This row!       <td >
                    Qty: <input type="number" className='table-input' name="inputs" value={this.state.inputs[a]} onChange={()=>this.handleTableInput(a)} />
                    <button type="button" className='buy-btn' onClick={()=>this.buyItem(a)}> Buy!</button>
                  </td>
                </tr>
              ))}
          </tbody>

Handling the input changes normally -This did not work when passing this.state.inputs[a] as the value as other rows would change as well:

handleInputChange = (event) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;

this.setState({
  [name]: value
});

}

I thought to change the above function to something like this where a (my index) is passed into the function. The problem is that I am not sure how to access the 'event' types like in the above generic function and thus not sure how to access the value that the user has input.

  handleTableInput = (ind) => {
const {inputs} = this.state;

inputs[ind] = "value from table input";
this.setState({inputs: inputs}) 

}

Thank you for any help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source