I have a simple react component with the table which I add row and delete row dynamically in table but when I change or type a text in input I got error:( When I run my application I get the following warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch........
Also in react tools, state shows rows as array thats ok when I type first cell its update it then wanna type second cell first one disappear :(
class App extends Component {
state = {
rows: [{}]
}
handleChange = idx => e => {
const { name, value } = e.target;
const rows = [...this.state.rows];
rows[idx] = {
[name]: value
};
this.setState({
rows
});
};
handleAddRow = () => {
const item = {
columnName: "",
dataType: "",
values: ""
};
this.setState({
rows: [...this.state.rows, item]
});
};
handleRemoveRow = () => {
this.setState({
rows: this.state.rows.slice(0, -1)
});
};
handleRemoveSpecificRow = (idx) => () => {
const rows = [...this.state.rows]
rows.splice(idx, 1)
this.setState({ rows })
}
<thead>
<tr>
<th className="text-center"> # </th>
<th className="text-center"> Column Name </th>
<th className="text-center"> DataType </th>
<th className="text-center"> Values </th>
<th />
</tr>
</thead>
<tbody>
{this.state.rows.map((item, idx) => (
<tr id="addr0" key={idx}>
<td>{idx}</td>
<td>
<input
type="text"
name="columnName"
value={this.state.rows[idx].columnName}
onChange={this.handleChange(idx)}
className="form-control"
/>
</td>
<td>
<input
type="text"
name="dataType"
value={this.state.rows[idx].dataType}
onChange={this.handleChange(idx)}
className="form-control"
/>
</td>
<td>
<input
type="text"
name="values"
value={this.state.rows[idx].values}
onChange={this.handleChange(idx)}
className="form-control"
/>
</td>
<td>
<button
className="btn btn-outline-danger btn-sm"
onClick={this.handleRemoveSpecificRow(idx)}
>
Sil
</button>
</td>
</tr>
))}
</tbody>