Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input field target is null while accessing in onChange field in reactjs

Even if I am assigning value to name and value fields, event.target is getting as null. event.target.value is getting value but not any other.

    <input type= "text" 
       name= {value}
       value = {currentValue}
       onChange = { (e) => this.onInputChanged(e) } 
       disabled = { disabled }
    />

    onInputChanged = async (e) => {
       await this.setState({ currentValue: e.target.value })
       console.log('event', e.target);    //This is showing null
       this.props.onInputChange(e);
    }
like image 853
Shraddha J Avatar asked Sep 23 '19 09:09

Shraddha J


People also ask

How do you handle onChange in react JS?

import React from "react"; function App() { return ( <input type="text" name="firstName" onChange={event => console. log("onchange is triggered")} /> ); } export default App; Now whenever you type something into the text box, React will trigger the function that we passed into the onChange prop.

How do you set a value to null in react?

To type the useState hook with null initial value in React, use the hook's generic, e.g. const [name, setName] = useState<string | null>(null) . The state variable can be initialized to null and set to the specified type later on in your code.

Why we use Event target value in react?

target gives you the element that triggered the event. So, event. target. value retrieves the value of that element (an input field, in your example).


1 Answers

React reuses the synthetic event object so you can't use it in an async context as it is.

From the docs:

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

Note:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

You either need to extract the information synchronously or call event.persist() to persist the object before using it in an async context.

Extracting the value synchronously:

onInputChanged = event => {
   const value = event.target.value;
   (async () => {
       await this.setState({ currentValue: value });
       this.props.onInputChange(e);
   })();           
}

Persisting the event before using it in an async context:

onInputChanged = event => {
   event.persist();
   (async () => {
       await this.setState({ currentValue: e.target.value });
       console.log('event', e.target);
       this.props.onInputChange(e);
   })();           
}
like image 58
trixn Avatar answered Oct 04 '22 23:10

trixn