I never understood how that this works if it ever works
in my react I wrote <input onChange={()=>console.log(this.value)} />
Why doesn't it recognize this??? it tells me that it Cannot read property 'value' of undefined
onChange anyone help please :/
Asked
Active
Viewed 26 times
1

Nairi Areg Hatspanyan
- 631
- 6
- 16
-
React doesn't bind the function with the input element when calling it, so you'll need a reference to it. See `React.createRef()`: https://reactjs.org/docs/refs-and-the-dom.html – Mystical Jul 05 '20 at 14:07
-
(e)=>e.target.value is better I guess but thanks anyway :) – Nairi Areg Hatspanyan Jul 05 '20 at 14:20
1 Answers
2
React doesn't bind the event listener with the element.
So, the this
refers to the class Component in which its defined.
If it was in functional Component then this
it undefined
So if your trying to read input elements value use this,
<input onChange={e => console.log(e.target.value)} />
Read More, Function And Class Components

ezio4df
- 3,541
- 6
- 16
- 31
-
Yeah that's it my friend advised me also but i forgot to delete lol thanks – Nairi Areg Hatspanyan Jul 05 '20 at 14:19