Reputation: 1662
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
Upvotes: 2
Views: 3011
Reputation: 222
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}
/>
);
Upvotes: 1
Reputation: 4954
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" />;
}
Upvotes: 2