reactjstypescriptreact-nativeshopify

Shopify/restyle Pass variant value to child component


Apologies if this has been answered elsewhere. Is there a typesafe way to pass variant information to child components?

I am trying to create a custom Button component using the useRestyle hook as descriebd in the page https://shopify.github.io/restyle/fundamentals/components/custom-components. I have this code:

const Button = ({
  onPress,
  label,
  buttonType,
  variant,
  ...rest
}: Props) => {
  const props = useRestyle(restyleFunctions, {variant, ...rest});

I extracted out the variant, but passed it back to useRestyle as it expects the variant prop in the second parameter. I lose type safety though when I do so.

Eg: Button variant is 'primary' | 'secondary'. restyleFunctions shows the error:
The types of 'propertiesMap.variant' are incompatible between these types.
Type 'boolean | undefined' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.ts(2345)

Thank you.


Solution

  • I have managed to get the value as such:

    const {variant = 'primary'} = rest;
    const props = useRestyle(restyleFunctions, rest)
    

    Had to pass a default value as variant is an optional prop in Restyle.