React + TypeScript usage of className prop
Solution 1:
You can use the HTMLAttributes
type, for example:
class MyComponent extends React.Component<MyProps & React.HTMLAttributes<HTMLDivElement>, {}> {
render() {
return <div className={ this.props.className }>My Div</div>
}
}
That way you can pass any of the properties that a html element might need.
If you only need the className
property then you can do this:
class MyComponent extends React.Component<MyProps & { className: string }, {}> {
render() {
return <div className={ this.props.className }>My Div</div>
}
}
Or simply add it to your MyProps
type.
Solution 2:
For someone who are looking solution for functional components, as I was.
type Props = {
className?: string
}
const MyComponent: React.FC<Props> = (props) => (
<div className={props.className}>{props.children}</div>
)
export default MyComponent
or if you want to declare interface separately:
interface OnlyClassNameInterface extends React.FC<{className: string}> {}
const MyComponent: OnlyClassNameInterface = (props) => (
<div className={props.className}>{props.children}</div>
)
export default MyComponent
and you can move interface to another file
import React from 'react'
type MixProps<P> = P & {className?: string}
export interface OnlyClassNameInterface<P = {}> extends React.FC<MixProps<P> {}