Home > Software engineering >  Add props to Button in Mantine TypeScript
Add props to Button in Mantine TypeScript

Time:12-26

I would like to create a button that changes background color depending on what the page/path is.

To do this, I was thinking of passing a new prop (ex. selected) to the Button component in Mantine in TypeScript.

So far, I have tried extending the interface to include the default passed params:

interface ButtonProps extends ButtonStylesParams {
  selected?: boolean;
}

const AboutItem = styled(Button)<ButtonProps>`
  color: white;
  background-color: ${props => props.selected ? "#282828" : "transparent"};
`;

However, this gives me an error when I try and use the AboutItem component:

Type '{ children: string; selected: boolean; }' is not assignable to type 'IntrinsicAttributes & { theme?: Theme | undefined; } & ButtonProps'.
  Property 'children' does not exist on type 'IntrinsicAttributes & { theme?: Theme | undefined; } & ButtonProps'

I'm wondering what the correct way of doing this is?

CodePudding user response:

See Mantine docs about styled polymorphic components:

Emotion cannot correctly extract prop types from polymorphic components. To add styles to such components with @emotion/styled, you will need to redefine polymorphic component type with createPolymorphicComponent function

import { Button, createPolymorphicComponent } from '@mantine/core';

const StyledAboutItem = createPolymorphicComponent<'button', ButtonProps>(AboutItem);

() => (
    // Okay
    <StyledAboutItem selected={true}>
        Some children
    </StyledAboutItem>
);

Playground Link

  • Related