Search code examples
javascriptreactjssetstate

How to pass the "event" object to the functional version of "this.setState()"?


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.


Solution

  • 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.