this is my code, the value of this.state.year is not changing when onChange event is triggered in select. I don't know why. can any one help me out
import React, { Component } from 'react'
import './ReportGen.css'
export class ReportGen extends Component {
constructor() {
super();
this.state = {
year: 'Academic Year'
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({year: event.target.value});
}
handleSubmit(event) {
console.log(this.state);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<select className='drop-down' placeholder='academic year' name='0' onChange={(e) => this.handleChange}>
<option value="Academic Year" >Academic Year</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default ReportGen
when im changing the option and click submit, im still getting academic year as output in the console
CodePudding user response:
You're not actually calling the function:
(e) => this.handleChange
When you do something like this:
onSubmit={this.handleSubmit}
You don't call the function, but pass the function to the onSubmit
handler so it will be called when that event happens.
But when you do this:
onChange={(e) => this.handleChange}
You create your own function wrapped around the function you want to call. The function you created is passed to the onChange
handler so it will be called when that event happens. But what does *your function do? It becomes more clear if we change the syntax a bit:
onChange={function (e) {
this.handleChange;
}}
As you can see, your function does nothing. It just has a single reference to this.handleChange
but never invokes it. You can invoke it:
onChange={(e) => this.handleChange(e)}
Or, even simpler, so what you're already doing in the onSubmit
handler and just pass the function reference directly:
onChange={this.handleChange}
CodePudding user response:
You should pass the e
parameter to your function: onChange={(e) => this.handleChange(e)}