Using TypeScript Interface in React Components
Colby Garland
Posted on July 22, 2021
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>
};
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>
};
Now, when we import this component into another file, VS Code will know what props this component has. π
π πͺ π
π©
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.