Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>

like image 206
MR.Jeon Avatar asked Apr 23 '26 13:04

MR.Jeon


1 Answers

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);
};
like image 200
Nicholas Tower Avatar answered Apr 25 '26 01:04

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!