2

Doing some practice in React JS and noticed I need to assign e.target to a variable before being able to use it - but why? The first code snippet gives me the error: "TypeError: Cannot read property 'input' of null". I am confused.

handleSubmit = (e) => {
        e.preventDefault()
        console.log("Added")
        this.setState((prevState) => {
            return {
                items: prevState.items.concat([e.target.input.value]) // does not work
            }
        })
    }
handleSubmit = (e) => {
        e.preventDefault()
        console.log("Added")
        const target = e.target
        this.setState((prevState) => {
            return {
                items: prevState.items.concat([target.input.value]) // This works. Why?
            }
        })
    }
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
MoQa BianQa
  • 41
  • 1
  • 3

2 Answers2

4

Since Setstate is an async process and due to React's Event Pooling , the scope of the event will be lost by the time setState gets executed , unless you use event.persist().

You can read more about React Event Pooling: https://reactjs.org/docs/events.html

0

I believe because you are reading e in a callback function of setState(). setState() may have re-rendered the DOM and 'e' may no longer have a target or a value.

Sydney Y
  • 2,912
  • 3
  • 9
  • 15