Types for React Components with ComponentProps

One useful TypeScript utility type for React is ComponentProps.

It can help you quickly generate all your types for your React components.

I know before I discovered ComponentProps, I found typing my components painful...

This article will explore using ComponentProps to extract and reuse prop types from React components.

What is ComponentProps?

ComponentProps is a utility type in React that enables you to extract the prop types from a React component.

You access it by simply importing it from React:

import { ComponentProps } from "react";

Extracting Prop Types from Elements

The simplest usage of React.ComponentProps is grabbing the available props on a DOM element.

So if we wanted to have all the available props for a button element, we can simply grab them off the ComponentProps helper.

It'll make sense when you see it:

import { ComponentProps } from "react";

type ButtonProps = ComponentProps<"button">;

Now ButtonPropswill contain all the possible prop types for a button element.

This will work for all DOM elements, so you can use this to fetch your types quickly.

And if you wanted to extend this with some of your custom props you could do that by adding them to the types:

import { ComponentProps } from "react";

type CustomButtonProps = ComponentProps<"button"> & {
  logsHelloWorld: boolean;
};

const CustomButton = ({ logsHelloWorld, ...props }: CustomButtonProps) => {
  if (logsHelloWorld) {
    console.log("Hello world!");
  }
  return <button {...props} />;
};

Getting Props from a Component

What if we have a custom component and want to get the types?

We can do that easily using typeof with ComponentProps:

import { ComponentProps } from "react";

const CustomButton = (props: { logsHelloWorld: boolean }) => {
  if (logsHelloWorld) {
    console.log("Hello world!");
  }
  return <button>Hello!</button>;
};

// Now we want to grab those types:
type CustomButtonProps = ComponentProps<
  typeof CustomButton
>;

This can be very useful if you need to grab something from a library or don't want to declare the types manually.

Happy Coding!


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

TypeScriptTs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.