2

so I'm using the functional form of this.setState() where you pass a function that returns an object.

But when I try to bind the onChange on an input and do this ...

onInputChange = event => {
    this.setState(() => ({
        ...this.state,
        [event.target.name]: event.target.value
    }));
};

It throws an error saying that Cannot read property 'name' of null obviously the problem is in the event object, so how can I pass the event object to this.setState() ?

I tried this but it didn't work ...

onInputChange = event => {
    this.setState((prevState, event) => ({
        ...this.state,
        [event.target.name]: event.target.value,
    }));
};

However the only thing that worked for me was doing it like this ...

onInputChange = e => {
    const { name, value } = e.target;
    this.setState(() => ({
        ...this.state,
        [name]: value
    }));
};

But I doubt that this is the right way to dot it.

5
  • Your working solution looks good to me, I'd just go with that. The reason the previous example doesn't work is because the functional setState signature receives the previous state and current props as arguments, not the change event as you have it here. Commented Aug 11, 2018 at 17:05
  • Also you need to persist the event event.persist() otherwise it will be full of null values -> reactjs.org/docs/events.html Commented Aug 11, 2018 at 17:13
  • @James Oh, The solution that did work felt a bit like a hack to me and that should be a proper way to do it. I'm new to React, so I really didn't it was the right solution. I have a question, why the "event' object cannot be accessed inside of the this.setState()? Commented Aug 11, 2018 at 17:15
  • @James Where should I add "event.persist()" and what does it do? If you have an article or something that I can read it would be awsome. Commented Aug 11, 2018 at 17:16
  • setState do the merge of old state and object passed into setState, so i think in your case, ...this.state is not required, also new value is independent of prevState value so functional setState is not required here, you can directly use: this.setState({ [event.target.name]: event.target.value }) Commented Aug 11, 2018 at 17:20

1 Answer 1

2

Something like this should work

onInputChange = event => {
    event.persist();
    this.setState(() => ({
        ...this.state,
        [event.target.name]: event.target.value
    }));
};

Although I will say I like your last attempt best.

Here are docs about synth events in react -> https://reactjs.org/docs/events.html

Also the functional setState signature receives the component's current state and next props as arguments, not the (prevState, event) => { as you have it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.