Projects Blog

Extending HTML elements properties in React with TypeScript

In React, it’s common to create a component that accepts all native element props in addition to our custom ones. And, naturally, we don’t want to do this manually.

For this purpose, React offers a solution.

Generic type ComponentProps<T>

React provides a generic type ComponentProps<T> that extracts the type of the props from any element or component.

When extending a native DOM element, it’s essential to set the element’s name as the generic (T). Then, we extend this type with our custom properties types.

Example

Let’s create a component that extends the native button element. This MyButton component will include two props primary and size. Also, don’t forget to pass the props destructuring to the component!

MyButton/index.tsx
import styles from './styles.module.css'
import { ComponentProps } from 'react'
interface ComponentProps extends ComponentProps<'button'> {
primary?: boolean
size?: 'small' | 'medium' | 'large'
}
export default function MyButton({
primary = false,
size = 'medium',
children,
...props
}: ComponentProps) {
const style = `${styles.button} ${primary ? styles['button--primary'] : ''} ${size ? styles[`button--${size}`] : ''}`
return (
<button
className={style}
{...props}
>
{children}
</button>
)
}

And now, we can use the component with both native and custom properties.

Page/index.tsx
import MyButton from './MyButton'
function onClick(e: React.MouseEvent<HTMLElement>) {
alert('Hello!')
}
export function MyPage() {
return (
<MyButton
size='medium'
onClick={onClick}
type='button'
disabled
>
Click me!
</MyButton>
)
}

Using this React type helper will greatly facilitate and expedite the development of components where we want to extend native elements.

I hope you found this article useful.

Happy coding! 🚀

Related posts