Last active
January 25, 2024 12:25
-
-
Save mfal/88fe927f2061d22425cc78fcec8d260f to your computer and use it in GitHub Desktop.
Extend regular HTML Elements with React & TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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")}/>; |
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
Nice one! Thanks!
Do you think there is a way to import this in a global.d.ts to avoid importing everytime the types?