Home > Software design >  Can't forward component property to styled Mui Button
Can't forward component property to styled Mui Button

Time:09-13

I've got a styled MUI Button:

const SecondaryButton = styled(Button)<ButtonProps>(({ theme }) => ({
  ...
}));

export default SecondaryButton;

If I use it like this:

<label htmlFor="contained-button-file">
   <input id="contained-button-file" multiple type="file" hidden onChange={this.selectFiles} />
      <SecondaryButton component='span'>
            Dateiauswahl
       </SecondaryButton>
</label>

I get the following typescript error:

Type '{ children: string; component: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "error" | ... 5 more ... | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & Omit<...> & CommonProps & Omit<...> & MUIStyledCommonProps<...>'.
Property 'component' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "error" | ... 5 more ... | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & Omit<...> & CommonProps & Omit<...> & MUIStyledCommonProps<...>'

If I use the Standard MUI Button instead there is no error. As far as I understand my styled Button should just forward the properties. Hence, it should work.

Any help is appreciated.

CodePudding user response:

As mentioned in the doc, due to some limitations, we have to bypass this by type casting, at least at the moment of this writing

const SecondaryButton = styled(Button)(({ theme }) => ({
  // ...
})) as typeof Button;
    ^^^^^^^^^^^^^^^^

export default SecondaryButton;

References

Complications with the component prop

  • Related