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

onInput event type on TypeScript / React

I am trying to use onInput on a generic Input component I’ve created, everytime I add a DOM event I have a little fight with TypeScript.

This is my component, Input.tsx:

import React, { ChangeEvent, FormEvent } from 'react'

import { InputStyled } from './Input-style'

type InputProps = {
  name: string
  value: string | number
  type?: string
  placeholder?: string
  onInput?: (e: FormEvent<HTMLInputElement>) => void
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void
}

export const Input = (props: InputProps) => (
  <InputStyled
    type={props.type ? props.type : 'text'}
    name={props.name}
    id={props.name}
    placeholder={props.placeholder}
    value={props.value}
    onInput={props.onInput}
    onChange={props.onChange}
   />
)

The problem I am having is that when using the onInput event, it says Property 'value' does not exist on type 'EventTarget'

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

import React from 'react'
import { Input } from '@components'

export const Main = () => {
  const [rate, setRate] = useState<number>(0)

  return (
    <Input
      type='number'
      name='Rate'
      value={rate}
      placeholder='Decimal number'
      onInput={e => setRate(Number(e.target.value))}
    />
  )
}

>Solution :

Explicitly typing the parameter of the handler works:

<Input
  onInput={(event: React.ChangeEvent<HTMLInputElement>) => setRate(event.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