I have a table where I need to make a list of input elements. They will have a default value and you can change their value from max number(default value) to 0 or send this maxNumber. Next to input elements is send button. The Button will get value from the input element and send it to API. Here is part of my code:
const [valueInput,setValueInput]=React.useState(0);
{array.map((x) => (
<TableRow
key={x.id}
>
<TableCell>{x.maxNumber}</TableCell>
<TableCell>
<input
key={x.id}
value ={valueInput}
onChange={ event => {
setValueInput(event.target.value);
parseInt(event.target.value,valueInput)
}}
type="number"
min="0"
max= {x.maxNumber}
/>
<IconButton
key={x.id}
onClick={() => {
team.setTeamNumber(x.id,valueInput);
}}>
<Check />
</IconButton>
</TableCell>
</TableRow>
))}
Can anyone help me how to set valueInput to be x.maxNumber - from the array, or any advice on how can I solve this without useState.
You can put the table row with input into a separate component and have the input state there. Then pass the row id and the input value up to the parent component on the change. For example
function TableRow({ id, inputValue, onInputChange }) {
const [inputVal, setInputVal] = React.useState(inputValue);
function handleInputChange(e) {
setInputVal(e.target.value);
onInputChange(id, e.target.value);
}
return (
<tr>
<td style={{ 'border': '1px solid black' }}>{inputValue}</td>
<td style={{ 'border': '1px solid black' }}>
<input type="number" value={inputVal} onChange={handleInputChange} />
</td>
</tr>
);
}
function Table() {
const rowsArr = [
{ id: '123', maxNum: 1 },
{ id: '456', maxNum: 2 }
];
function handleInputChange(inputId, inputValue) {
console.log(`Input with id ${inputId} has value ${inputValue}`);
}
return (
<div>
<table style={{ 'border': '1px solid black' }}>
<tbody>
{rowsArr.map((x) => <TableRow key={x.id} id={x.id} inputValue={x.maxNum} onInputChange={handleInputChange} />)}
</tbody>
</table>
</div>
);
}
function App() {
return (
<div>
<Table />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>