Home > Net >  How do I add type to onChange & onClick functions in typescript react
How do I add type to onChange & onClick functions in typescript react

Time:11-28

I have defined a component

type Props = {
  label:string,
  autoFocus:boolean,
  onClick:(e: React.ClickEvent<HTMLInputElement>) => void,
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
}

const Input = ({ handleChange, label, autoFocus, handleClick  }:Props) => (
    <TextField
      onChange={handleChange}
      required
      label={label}
      autoFocus={autoFocus}
      onClick={handleClick}
      }
    />
);

I am converting my react components into typescript for the first, I am a bit confused about what type should I write for functions that I am retrieving it props, Above type Props initiation, I get that string & boolean but how someone should handle event function typing

CodePudding user response:

You can define handleClick as React.MouseEventHandler<HTMLInputElement>:

import { TextField } from "@material-ui/core";
import React from "react";

type Props = {
  label: string;
  autoFocus?: boolean;
  handleClick?: React.MouseEventHandler<HTMLInputElement>;
  handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
};

const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
  <TextField
    onChange={handleChange}
    required
    label={label}
    autoFocus={autoFocus}
    onClick={handleClick}
  />
);

export default function App() {
  return <Input label="CustomInput" />;
}

Edit hopeful-estrela-4jhlo

CodePudding user response:

As we want to use MUI to support the types and to be a single source of truth, I'd suggest inferring the types from material UI itself, instead of creating separate types.

import { TextField, TextFieldProps } from '@mui/material';

type Props = {
    handleChange: TextFieldProps['onChange'];
    handleClick: TextFieldProps['onClick'];
    label: TextFieldProps['label'];
    autoFocus: TextFieldProps['autoFocus'];
};

const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
    <TextField
        onChange={handleChange}
        required
        label={label}
        autoFocus={autoFocus}
        onClick={handleClick}
    />
);
  • Related