Skip to content

Instantly share code, notes, and snippets.

@mfal
Last active January 25, 2024 12:25
Show Gist options
  • Save mfal/88fe927f2061d22425cc78fcec8d260f to your computer and use it in GitHub Desktop.
Save mfal/88fe927f2061d22425cc78fcec8d260f to your computer and use it in GitHub Desktop.
Extend regular HTML Elements with React & TypeScript
// We extend from React.HTMLAttributes to get all the HTML attributes
// Don't extend React.HTMLProps!
export interface IGreenBoxProps extends React.HTMLAttributes<HTMLDivElement> {
title: string;
}
class GreenBox extends React.Component<IGreenBoxProps, void> {
public render() {
// If you don't spread children and title, the restProps
// still contain these props and compiler will say "no"
const {children, title, ...divAttributes} = this.props;
return (
<div {...divAttributes} style={{backgroundColor: "green"}}>
<h1>{title}</h1>
{children}
</div>
);
}
}
const myGreenBox = <GreenBox title="Hello" onClick={() => alert("Hello")}/>;
@PFight
Copy link

PFight commented Jun 25, 2020

Type React.HTMLAttributes<HTMLDivElement> does not includes ref field and some other. Correct code is:

export interface IGreenBoxProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {

@justinmahar
Copy link

justinmahar commented May 19, 2021

For anyone coming across this, you can also use the react-html-props library for concise types for all HTML props.

This makes it super easy to type your components with types like DivProps, ImgProps, HeadingProps, etc, with or without a ref.

Check it out here: react-html-props

@sauldeleon
Copy link

For anyone coming across this, you can also use the react-html-props library for concise types for all HTML props.

This makes it super easy to type your components with types like DivProps, ImgProps, HeadingProps, etc, with or without a ref.

Check it out here: react-html-props

Nice one! Thanks!

Do you think there is a way to import this in a global.d.ts to avoid importing everytime the types?

@Barna-Molnar
Copy link

Barna-Molnar commented Apr 26, 2022

Or if you know that you are not going to use ref, you don't need and this works perfectly:
extends ComponentPropsWithoutRef<'div'>
or : DetailedHTMLFactory<HTMLAttributes<HTMLDivElement>, HTMLDivElement> <= this is the exact react definition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment