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

Argument of type 'string' is not assignable to parameter of type 'ChangeEventHandler<HTMLInputElement>'

I am learning React Typescript, and I have defined a onChange event props. But getting below mentioned errror.

Input.tsx

type InputProps ={
    value: string,
    handleChange: (event:React.ChangeEventHandler<HTMLInputElement>)=> void;
}

export const Input = (props: InputProps) =>{
    const handleInputChange:React.ChangeEventHandler<HTMLInputElement> =(event)=>{
        console.log(event.currentTarget.value);
        props.handleChange(event.currentTarget.value)//Having issue in this line
    }
    return <input type="text" value={props.value} onChange={handleInputChange} />
}

App.tsx

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

<Input handleChange={value=> console.log(value)} value=""/>

Error: Argument of type ‘string’ is not assignable to parameter of type ‘ChangeEventHandler’.
enter image description here

>Solution :

You’ve defined handleChange as a function that accepts an event object:

type InputProps ={
    value: string,
    handleChange: (event:React.ChangeEventHandler<HTMLInputElement>)=> void;
// −−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

But you’re trying to pass it a string:

props.handleChange(event.currentTarget.value)//Having issue in this line
// −−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^

Either define the function so it accepts a string, or pass it the event object. I would do the former, define it so that it accepts a string:

type InputProps = {
    value: string;
    handleChange: (value: string) => void;
// −−−−−−−−−−−−−−−−^^^^^^^^^^^^^
};

Playground link

But if you prefer, pass it the event object:

type InputProps = {
    value: string;
    handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
// −−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};

// ...

props.handleChange(event);
// −−−−−−−−−−−−−−−−^^^^^

Notice that the event parameter is ChangeEvent<HTMLInputElement>, not ChangeEventHandler<HTMLInputElement>.

Playground link

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