simbro
simbro

Reputation: 3672

React: Cannot set state from onchange event handler on form select

I have a react component that is structured like this. I would like to capture the user's selection when they select from a drop-down.

I get the following error message when I try it:

"Uncaught TypeError: Cannot read property 'setState' of undefined"

I am following the example in the docs, so where am I going wrong?

export default class SearchPage extends Component {

....

handleChange(e) {
    this.setState({
        params: {
            ...this.state.params,
            [e.target.name]: e.target.value
        }
    })
}

render() {
    const { county, cause, activity } = this.state

    return (
        <div className="searchpage">
            <form>
               <select name="county" onChange={this.handleChange}
               .....

Upvotes: 1

Views: 2571

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

handleChange wasn't bound to the instance. You need either use inline arrow function that will capture this lexically

<select name="county" onChange={e => this.handleChange(e)}

or (recommended way) bind methods within constructor.

constructor() {
   super();
   this.handleChange = this.handleChange.bind(this);
}

Upvotes: 3

Michael Rasoahaingo
Michael Rasoahaingo

Reputation: 1089

This is another trick to avoid binding your function with .bind(this) or some decorators or create anonymous function like () => myfunc()

handleChange => (e) { }

Then you can use this as you want inside

Upvotes: 0

Related Questions