I am trying to update the values in the form in child component to send to the api if I update an user but I am unable to change any values in the form and it only add or removes one character if I see the states. How can I update the values? using defaultValue solves it but it changes the input to be uncontrolled which i do not want.
...
#Parent Class
import React from "react";
import "./styles.css";
import Child from "./child";
export default class Parent extends React.Component {
constructor() {
super();
this.state = {
user: {
id: [1, 2, 3, 4, 5],
name: ["john", "wick", "ellen", "fork", "gow"]
}
};
}
render() {
return <Child user={this.state.user}> </Child>;
}
}
#Child Class
import React from "react";
import "./styles.css";
export default class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {
id: "",
name: ""
}
};
}
handleSubmit = e => {
e.preventDefault();
};
handleChange = e => {
const data = { ...this.state.user };
data[e.currentTarget.name] = e.currentTarget.value;
this.setState({ user: data });
};
render() {
console.log(this.state);
console.log(this.props);
return (
<>
{this.props.user.id.map((id, index) => {
return (
<form onSubmit={this.handleSubmit}>
<label> id </label>
<input
type="text"
value={
this.props.user.id[index] !== "undefined"
? this.props.user.id[index]
: this.state.user.id
}
onChange={this.handleChange}
/>
<br />
<label> name </label>
<input
type="text"
value={
this.props.user.name[index] !== "undefined"
? this.props.user.name[index]
: this.state.user.name
}
onChange={this.handleChange}
/>
</form>
);
})}
}
</>
);
}
}
...
my sample code is
https://codesandbox.io/s/focused-shamir-y85v9?file=/src/parent.js:0
{ id: ###, name: 'XXX' }, with a handler defined in parent to be passed to children components?nameattribute to all the inputs it becomes a trivial matter to match an input with a data field in a user object in state by index.