skip to Main Content

I’m having trouble figuring out what the type of the parameter e in function handleChange should be. I have handleChange passed as a prop to the form componentI made which is then attached to the onChange prop of my input an select fields.

If anyone needs my form components code I can attach that to a reply. Thanks in advance.

type Info = {
  studentName: string
  email: string
  time: string
  subject: string
}

const Schedual = () => { 
  const [info, setInfo] = useState<Info>()

  //find type
  const handleChange = (e: any) =>{
    const {name, value} = e.target
    //find type
    setInfo((prev: any)=> {
      return{...prev, [name]: value}
    })
  }

  const handleSchedule = (e: React.FormEvent) => {
    e.preventDefault()
    console.log(info)
  }

  return (

    <>
      <div>
        <Form title="Schedule Here" onSubmit={handleSchedule} isSelectVisible={true} onChange={handleChange}/>
      </div>
      <ButtonLink text="Back" path="/" icon={<TbArrowBackUp />} />
      <ButtonLink text="Issues" path="/issues" icon={<TbArrowForwardUp />} />
    </>
  )
}


export default Schedual

3

Answers


  1. It looks like your onChange() gets called in the input field. Try using the HTMLInputElement type for the event parameter in onChange();

    const handleChange = (e: HTMLInputElement) =>{
        const {name, value} = e.target
        setInfo((prev: Info)=> {
          return {...prev, [name]: value}
        })
      }
    
    Login or Signup to reply.
  2. It will be the first parameter of the Form’s onSubmit

    type EV = Parameters<React.ComponentProps<typeof Form>['onSubmit']>[0]
    const handleChange = (e: EV) => {
     // ...
    }
    
    Login or Signup to reply.
  3. For more details, you can refer to this blog: https://www.carlrippon.com/React-event-handlers-with-typescript/

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setInfo((prev) => ({ ...prev, [name]: value }));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search