-
-
Save mfal/88fe927f2061d22425cc78fcec8d260f to your computer and use it in GitHub Desktop.
| // 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")}/>; |
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
For anyone coming across this, you can also use the
react-html-propslibrary 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 aref.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?
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
Type
React.HTMLAttributes<HTMLDivElement>does not includesreffield and some other. Correct code is: