Event target is null inside functional setState. That is because of React doing event pooling – all the event’s fields get nullified after the callback is done, so you observe them as nulls in the asynchronous setState callback.
Please copy your event data to a variable or call event.persist() to disable this behaviour.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | class Example extends React.Component { constructor() { super() this.state = { } } handleInputChangeCopy = (e) => { const val = e.target.value; console.log('in callback'); console.log(e.target.value); this.setState(function (prevState, props) { console.log('in async callback'); console.log(val); return { searchValue: val } }) } handleInputChangePersist = (e) => { e.persist(); console.log('in callback'); console.log(e.target.value); this.setState(function (prevState, props) { console.log('in async callback'); console.log({ isNull: e.target === null }) console.log(e.target.value); return { searchValue: e.target.value } }) } handleInputChange = (e) => { console.log('in callback'); console.log(e.target.value); this.setState(function (prevState, props) { console.log('in async callback'); console.log({ isNull: e.target === null }) console.log({ event: e }); console.log(e.target.value); return { searchValue: e.target.value } }) } render() { return ( <div> <div>Copy example</div> <input type="text" onChange={this.handleInputChangeCopy} /> <p>Persist example</p> <input type="text" onChange={this.handleInputChangePersist} /> <p>Original example - please note nullified fields of the event in the async callback. <small>Breaks the example, please re-run after a Script error</small></p> <input type="text" onChange={this.handleInputChange} /> <div style={{height: 300}} /> </div> ) } } ReactDOM.render( <Example searchValue={"test"} />, document.getElementById('app') ) |
1 2 3 4 | <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.