Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Extend React component props for styled component element

i'm trying to extend a react components props in TypeScript so that it contains all the normal html button attributes, as well as react specific stuff like ref

My understanding is that the type React.HTMLProps is what i need, (React.HTMLAttributes doesn't contain ref)

However, when trying to pass my props to a styled component the compiler complains.

My attempt 👇🏼 Codesandbox example: https://codesandbox.io/s/cocky-cohen-27cpw

enter image description here

like image 851
Samuel Avatar asked Aug 09 '19 06:08

Samuel


2 Answers

Couple of things.

Change the typing to:

interface Props extends React.ComponentPropsWithoutRef<'button'> {
  loading?: boolean
  secondary?: boolean
  fullWidth?: boolean
}

That should fix the issue for you. I forked your sandbox and it gets rid of the error.

There is also a SO post that this come from that you can use: Using a forwardRef component with children in TypeScript - the answer details one way but also mentions the answer 1.

like image 106
rrd Avatar answered Oct 28 '22 11:10

rrd


Thanks to all who helped me get to the bottom of this. What i actually needed was to be able to forward refs to my underlying styled component, i achieved this in TypeScript like this:

enter image description here

like image 9
Samuel Avatar answered Oct 28 '22 12:10

Samuel