[React Typescript] Useful React Prop Type Examples
Relevant for components that accept other React components as props.
export declare interface AppProps {
children?: React.ReactNode; // best, accepts everything React can render
childrenElement: JSX.Element; // A single React element
style?: React.CSSProperties; // to pass through style props
onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target
// more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring
props: Props & React.ComponentPropsWithoutRef<"button">; // to impersonate all the props of a button element and explicitly not forwarding its ref
props2: Props & React.ComponentPropsWithRef<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref
}
Example:
import React from 'react';
export const Button = ({
className,
...rest
}: React.ComponentPropsWithoutRef<'button'>) => {
return (
<button {...rest} className={`default-classname ${className}`}></button>
);
};
const Parent = () => {
return <Button onClick={() => {}} type="button"></Button>;
};