Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get input value use React.ChangeEventHandler<HTMLInputElement> in react typescript

My code is

import React, { useState } from "react";

function App() {
  const [inputValue, setInputValue] = useState<string>("");
  const handleInputValue = (e: React.ChangeEventHandler<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  return (
    <div className="App">
      <div>
        <input name="name" onChange={handleInputValue} />
      </div>
      <p>{inputValue}</p>
    </div>
  );
}

export default App;

when i use e:any working well but use the e type React.ChangeEventHandler not working

And this is error message

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Property ‘target’ does not exist on type ‘ChangeEventHandler’.

 Type '(e: React.ChangeEventHandler<HTMLInputElement>) => void' is not assignable to type 'ChangeEventHandler<HTMLInputElement>'.
  Types of parameters 'e' and 'event' are incompatible.
    Type 'ChangeEvent<HTMLInputElement>' is not assignable to type 'ChangeEventHandler<HTMLInputElement>'.
      Type 'ChangeEvent<HTMLInputElement>' provides no match for the signature '(event: ChangeEvent<HTMLInputElement>): void'.
    27 |       <div>
  > 28 |         <input name="name" onChange={handleInputValue} />
       |                            ^^^^^^^^
    29 |       </div>

>Solution :

const handleInputValue = (e: React.ChangeEventHandler<HTMLInputElement>) => {
    setInputValue(e.target.value);
};

The type ChangeEventHandler is for the entire function, not just the event that’s passed into it. So you either need to do this:

const handleInputValue: React.ChangeEventHandler<HTMLInputElement> = (e) => {
  setInputValue(e.target.value);
};

Or this:

const handleInputValue = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading