[React Typescript] ComponentProps

发布时间 2023-05-07 16:10:53作者: Zhentiw

Blog: https://www.totaltypescript.com/react-component-props-type-helper

 

Get any Prop type from html element:

import { ComponentProps } from "react";

type ButtonProps = ComponentProps<"button">;

 

Get props type from a Component

const SubmitButton = (props: { onClick: () => void }) => {
  return <button onClick={props.onClick}>Submit</button>;
};

type SubmitButtonProps = ComponentProps<
  typeof SubmitButton
>;

 

With Ref:

Refs in React let you access and interact with the properties of an element. Often, it's used with form elements like inputs and buttons to extract their values or set their properties. The ComponentPropsWithRef does exactly what it says - provide the component props with its associated ref.

type InputProps = ComponentPropsWithRef<"input">;