Borislav Hadzhiev
Wed Apr 06 2022·2 min read
Photo by Jeison Higuita
The React.js error "Property 'value' does not exist on type EventTarget"
occurs when the type of the event parameter is incorrect. To solve the error,
type the event as React.ChangeEvent<HTMLInputElement>
. You can then access the
value as event.target.value
.
Here is an example of how the error occurs.
function App() { // 👇️ incorrect event type const handleChange = (event: Event) => { console.log(event.target?.value); }; return ( <div> {/* ⛔️ Property 'value' does not exist on type 'EventTarget'. */} <input onChange={handleChange} type="text" id="message" /> </div> ); } export default App;
To solve the error, we have to type the event
parameter as
React.ChangeEvent<HTMLInputElement>
.
function App() { // ✅ correct event type const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { console.log(event.target.value); }; return ( <div> <input onChange={handleChange} type="text" id="message" /> </div> ); } export default App;
The ChangeEvent
type in React has a target
property that refers to the
element on which the event is dispatched.
The easiest way for you to find out what the type of an event is, is to write
the event handler inline and hover over the event
parameter in the function.
function App() { // 👇️ event is written inline return ( <div> <input onChange={e => console.log(e.target.value)} type="text" id="message" /> </div> ); } export default App;
The screenshot shows that when we hover over the e
variable in the inline
event handler, we get the correct type for the event.
TypeScript is always going to be able to infer the event
type on an inline
event handler because you have the type definitions for React installed.
# 👇️ with NPM npm install --save-dev @types/react @types/react-dom # ---------------------------------------------- # 👇️ with YARN yarn add @types/react @types/react-dom --dev