DEV Community

Colby Garland
Colby Garland

Posted on

3

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. 🎉

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

đź‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay