Using TypeScript Interface in React Components

colbygarland

Colby Garland

Posted on July 22, 2021

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. πŸŽ‰

πŸ’– πŸ’ͺ πŸ™… 🚩
colbygarland
Colby Garland

Posted on July 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related