Reputation: 649
I am facing an issue when I try to set the state of a component in the Input field. I have tried by setting the Object values in the constructor but that didn't work either. If I remove the prop the input field is not getting any value. I have posted my JS code below.
Input Component:
<div className="form__group">
<input
className="form__field"
id={props.name}
name={props.name}
type={props.inputtype}
value={props.value}
onChange={props.handleChange}
placeholder={props.placeholder}
{...props}
/>
<label htmlFor={props.name} className="form__label">{props.placeholder}</label>
</div>
JSX Code:
<Input
inputtype={"text"}
title={"Full Name : "}
name={"name"}
value={this.state.newUser.name}
handleChange={this.handleInput}
placeholder={"Enter your Name"}
/>{" "}
JS Code:
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
newUser: {
name: "",
age: "",
gender: "",
skills: [],
about: ""
},
this.handleInput = this.handleInput.bind(this);
}
handleInput(e) {
let value = e.target.value;
let name = e.target.name;
this.setState(
prevState => ({
newUser: {
...prevState.newUser,
[name]: value
}
}),
() => console.log(this.state.newUser)
);
}
}
Upvotes: 5
Views: 10569
Reputation: 196
handleChange is passed on because of {...props}
, and is not a valid for the input element.
If you spread out the props in the parameters:
const Input = ({ name, inputType, value, handleChange, placeholder, ...props}) => {
and then
<input
className="form__field"
id={name}
name={name}
type={inputType}
value={value}
onChange={handleChange}
placeholder={placeholder}
{...props}
/>
Upvotes: 9
Reputation: 458
Actually there is a problem in your JSX (handleChange instead of onChange, but it is not the main thing)
So in my example your final code should look like this
handleInput = (input) => {
this.setState({ newUser: { [input.target.name]: input.target.value } });
}
<Input
inputtype="text"
title="Full Name : "
name="name"
value={this.state.newUser.name}
onChange={this.handleInput}
placeholder="Enter your Name"
/>
Upvotes: 0