Categories
TypeScript Answers

How to add the className prop to a component with React and TypeScript?

Spread the love

Sometimes, we want to add the className prop to a component with React and TypeScript.

In this article, we’ll look at how to add the className prop to a component with React and TypeScript.

How to add the className prop to a component with React and TypeScript?

To add the className prop to a component with React and TypeScript, we can add the React.HTMLAttributes type into our prop type.

For instance, we write

class MyComponent extends React.Component<
  MyProps & React.HTMLAttributes<HTMLDivElement>,
  {}
> {
  render() {
    return <div className={this.props.className}>My Div</div>;
  }
}

to set the prop type of MyComponent to MyProps & React.HTMLAttributes<HTMLDivElement>.

MyProps & React.HTMLAttributes<HTMLDivElement> is an intersection of the MyProps and React.HTMLAttributes<HTMLDivElement> types.

So the props that are in both types would be allowed in the combined types.

React.HTMLAttributes<HTMLDivElement> has the valid attributes of a div element as its properties, which includes className.

Conclusion

To add the className prop to a component with React and TypeScript, we can add the React.HTMLAttributes type into our prop type.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.