(React) Property 'value' does not exist on type EventTarget

avatar

Borislav Hadzhiev

Wed Apr 06 20222 min read

(React) Property 'value' does not exist on type EventTarget #

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.

property value does not exist on type eventtarget

Here is an example of how the error occurs.

App.tsx
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>.

App.tsx
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.

App.tsx
function App() { // 👇️ event is written inline return ( <div> <input onChange={e => console.log(e.target.value)} type="text" id="message" /> </div> ); } export default App;

react event type inline

The screenshot shows that when we hover over the e variable in the inline event handler, we get the correct type for the event.

This approach works for all event handlers and once you know the correct type of the event, you can extract your handler function and type it correctly.

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.

shell
# 👇️ with NPM npm install --save-dev @types/react @types/react-dom # ---------------------------------------------- # 👇️ with YARN yarn add @types/react @types/react-dom --dev
Use the search field on my Home Page to filter through my more than 1,000 articles.