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

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.