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")}/>;
@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