React Typescript input onChange event type?


I’m trying to get text from a input element, setting it to state and then rendering it back into the input box. However I think my event typing is wrong? I’ve searched online and tried implementing many solutions but none have worked so far. Any help is appreciated.

my component:

import React, { ChangeEvent, ChangeEventHandler, useState } from "react";

export default function Unidirectionflow() {
  const [state, setState] = useState("");
  const [state2, setState2] = useState("");
  const [state3, setState3] = useState("");
  const [state4, setState4] = useState("");
  const [state5, setState5] = useState("");

  function handleChange(e: ChangeEventHandler<HTMLInputElement>): void {
    setState((e.target as HTMLInputElement).value);
  }

  function handleChange2(e: {
    target: React.ChangeEventHandler<HTMLInputElement>;
  }) {
    setState2(e.target.value);
  }

  function handleChange3(e: React.FormEvent<HTMLInputElement>): void {
    setState2(e.currentTarget.value);
  }

  let handleChange4 = (e: React.FormEvent<HTMLInputElement>): void => {
    setState3((e.target as HTMLInputElement).value);
  };

  let handleChange5 = (event: ChangeEvent<HTMLInputElement>) => {
    setState5(event.currentTarget.value);
  };

  return (
    <main>
      <input type="text" value={state} onChange={() => handleChange} />
      <input type="text" value={state2} onChange={() => handleChange2} />
      <input type="text" value={state3} onChange={() => handleChange3} />
      <input type="text" value={state4} onChange={() => handleChange4} />
      <input type="text" value={state4} onChange={() => handleChange5} />
    </main>
  );
}


Typescript input onchange event.target.value

React TypeScript: Correct Types for onChange

Can't type in React TextField Input

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forms_and_events/

Source: React – Stack Overflow

November 20, 2021
Category : News
Tags: Events | input | reactjs | typescript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.