Home > other >  I am trying to read data from input field and set it to in state but again and again getting error
I am trying to read data from input field and set it to in state but again and again getting error

Time:12-27

const OnBlurHandler = (e: React.FocusEventHandler<HTMLInputElement>): void =>  {
        const petnames = e.target.name;
        const petvalues = e.target.value;
}

Property 'target' does not exist on type '(event: FocusEvent<HTMLInputElement, Element>) => void

CodePudding user response:

The event type is wrong, you should use React.FocusEvent<HTMLInputElement> instead.

CodePudding user response:

You can use this method to figure out how to create the type you need:

TS Playground

import {default as React} from 'react';

(<input onBlur={/* What should go here? */}></input>);
//      ^^^^^^
// You can find the type you need by hovering over the attribute name:
// In this case, it's: React.FocusEventHandler<HTMLInputElement> | undefined

// So, you can use the function type provided by React as the type annotation:
const handleBlur1: React.FocusEventHandler<HTMLInputElement> = (event) =>  {
  const {
    name, // string
    value, // string
  }= event.target;
};

// Or provide explicit parameter and return types for your own funciton:
const handleBlur2 = (event: React.FocusEvent<HTMLInputElement>): void =>  {
  const {
    name, // string
    value, // string
  }= event.target;
};

(<input onBlur={handleBlur1}></input>); // ok
(<input onBlur={handleBlur2}></input>); // ok
  • Related