Hello all,
I seem to be stuck with adding component={Link} to a button (where Link is imported from react-router-dom). I have created a component with different types of buttons (e.g. primary, secondary, tertiary etc.) to keep my code dry, but when I try to add the component to one of the buttons it has an error (see image below). Any suggestions for how to fix this? Many thanks in advance 🙂
#Add Button component
9 messages · Page 1 of 1 (latest)
So, what is the error?
There are a number of problems forwarding props to a button component. We're building a wrapper for the button so that we can keep our styles in one place. The code is:
import { Button, ButtonProps } from '@mantine/core'
export function SecondaryButton({ children, ...props }: ButtonProps) {
return (
<Button
loaderPosition="center"
variant="outline"
radius="xl"
size="xs"
sx={(theme) => ({
textAlign: 'center',
backgroundColor:
theme.colorScheme === 'dark'
? theme.colors.fawn[0]
: theme.colors.fawn[1],
color:
theme.colorScheme === 'dark'
? theme.colors.fawn[7]
: theme.colors.fawn[8],
borderColor: theme.colors.fawn[7],
borderRadius: theme.radius.md,
marginRight: theme.spacing.md,
})}
{...props}
>
{children}
</Button>
)
}
When we try and use it with the polymorphic component prop, we get this error:
(property) component: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>
Type '{ children: string; component: ForwardRefExoticComponent<LinkProps & RefAttributes<HTMLAnchorElement>>; to: string; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'.
Property 'component' does not exist on type 'IntrinsicAttributes & ButtonProps'.ts(2322)
I've edited my message to include the TypeScript error we're getting.
We're not trying to create a new polymorphic component, we're just trying to forward the props through and aren't able to find the correct prop type for our component to allow this
Is something like this a better solution??
import { Button, ButtonProps } from '@mantine/core'
import { useState } from 'react'
function SecondaryButton<C>({ children, ...props }: ButtonProps) {
return (
<Button<C>
loaderPosition="center"
variant="outline"
radius="xl"
size="xs"
sx={(theme) => ({
textAlign: 'center',
backgroundColor:
theme.colorScheme === 'dark'
? theme.colors.fawn[0]
: theme.colors.fawn[1],
color:
theme.colorScheme === 'dark'
? theme.colors.fawn[7]
: theme.colors.fawn[8],
borderColor: theme.colors.fawn[7],
borderRadius: theme.radius.md,
marginRight: theme.spacing.md,
})}
{...props}
>
{children}
</Button>
)
}
With the generics added
If you need your component to support component prop then you need to make new polymorphic component with createPolymorphiComponent function.
Ok we'll give it a go