Reputation: 71
I have this form where I want the name and gender of the user and I change state accordingly but my code seems to fail as the output don't match what i want. Here is the code.
class Addoption extends React.Component{
constructor(props){
super(props);
this.state={
name:'',
gender:''
};
this.handleaddoption=this.handleaddoption.bind(this);
}
handleaddoption(event){
event.preventDefault();
const nameofuser=event.target.elements.nametext.value;
const genderofuser=event.target.elements.gendertext.value;
this.setState({
name:nameofuser,
gender:genderofuser
});
console.log(this.state.name);
console.log(this.state.gender);
}
render(){
return(
<div>
<form >
<input type="text" name="nametext" placeholder="name" onChange={this.handleaddoption}/>
<input type="text" name="gendertext" placeholder="gender" onChange={this.handleaddoption}/>
</form>
</div>
);
}
}
export default App;
When the user enters the name and the age ,I don't see his age and name in console instead error which says cannot read Cannot read property 'nametext' of undefined. I tried one more method even that doesn't seem to work.
handleaddoption(event){
event.preventDefault();
const nameofuser=event.target.elements.nametext.value;
const genderofuser=event.target.elements.gendertext.value;
this.setState({
name:nameofuser,
gender:genderofuser
});
console.log(this.state.name);
console.log(this.state.gender);
}
render(){
return(
<div>
<form onSubmit={this.handleaddoption}>
<input type="text" name="nametext" placeholder="name" />
<input type="text" name="gendertext" placeholder="gender"/>
</form>
</div>
);
}
}
Upvotes: 0
Views: 48
Reputation: 143
You need to handle the event a little different.
Your handler function receives an event object, and the event.target is actually the input.
Change your input names so you can directly reference the state with them.
Then check out the component lifecycle, you can't see the updates because of how the component rendering works in react. Notice I used the componentDidUpdate method which runs after the setState is completed and there the logs show the new state.
Here's the link to the lifecycle docs: https://reactjs.org/docs/state-and-lifecycle.html
import React from 'react'
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { name: '', gender: '' }
this.handleChange = this.handleChange.bind(this)
}
componentDidUpdate() {
console.log('gender 1', this.state.gender)
console.log('name 1', this.state.name)
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
console.log('gender', this.state.gender)
console.log('name', this.state.name)
}
render() {
return (
<form action="">
<input type="text" name="gender" value={this.state.gender || ''} onChange={this.handleChange}/>
<input type="text" name="name" value={this.state.name || ''} onChange={this.handleChange}/>
</form>
)
}
}
export default MyComponent
Upvotes: 1