Skip to main content

Snippets

React and TypeScript Component Snippets

Building robust React applications depends on strong typing and consistent component patterns. These snippets illustrate best practices for defining component props with TypeScript, including children handling and state management.

Typed components

Try to keep one file with one named export when possible. An exception can be when a default export is required for framework specific reasons.

Without children

type Props = {
label: string;
};
export const Button = ({ label }: Props) => {
return <button>{label}</button>;
};

With children

import { PropsWithChildren } from 'react';
type Props = {
prop: boolean;
};
export const Button = ({ children }: PropsWithChildren<Props>) => {
return <button>{children}</button>;
};