DEV Community

Colby Garland
Colby Garland

Posted on

Using TypeScript Interface in React Components

One of my favorite parts of writing React components with TypeScript is interfacing all of my components.

Take a simple component:

export const MyButton = (props) => {
  return <button class={props.type} id={props.id}>{props.title}</button>
};
Enter fullscreen mode Exit fullscreen mode

So our component, <MyButton /> takes a type, an id, and a title. This is fine, however if I was importing this component into another file, how would my editor know what props this component takes?

Enter interface.

interface MyButtonProps {
  id: number;
  type: string;
  title: string;
}
export const MyButton = (props: MyButtonProps) => {
  return <button class={props.type} id={props.id}>{props.title}</button>
};
Enter fullscreen mode Exit fullscreen mode

Now, when we import this component into another file, VS Code will know what props this component has. 🎉

Discussion (0)