How do you add a linear gradient background to a native-base button?

Viewed 526

I'm trying to find a way of utilizing Native Base's button but I just want the background to be gradient. I can't seem to find the option nor can I find a nice injection point in the code.

https://github.com/GeekyAnts/NativeBase/issues/37

My current implementation looks like this but it has an issue in that the button is the text and not the full area.

import { Box, Button, IButtonProps, useThemeProps } from "native-base";
import React, { useCallback, useMemo, useState } from "react";
import type { GestureResponderEvent, LayoutChangeEvent } from "react-native";


export const GradientButton = ({
  children,
  colorScheme = "primary",
  ...buttonProps
}: IButtonProps): JSX.Element => {
  const buttonThemeProps = useThemeProps("Button", buttonProps);


  const [pressed, setPressed] = useState(false);

  const handlePressIn = useCallback(
    (e: GestureResponderEvent) => {
      setPressed(true);
      if (buttonProps.onPressIn) {
        buttonProps.onPressIn(e);
      }
    },
    [buttonProps]
  );

  const handlePressOut = useCallback(
    (e: GestureResponderEvent) => {
      setPressed(false);
      if (buttonProps.onPressOut) {
        buttonProps.onPressOut(e);
      }
    },
    [buttonProps]
  );
  const colors = useMemo(
    () =>
      pressed
        ? [`${colorScheme}.500`, `${colorScheme}.600`]
        : [`${colorScheme}.400`, `${colorScheme}.500`],
    [pressed]
  );

  return (
    <Box
      {...buttonThemeProps}
      overflow="hidden"
      bg={{
        linearGradient: {
          start: [0, 0],
          end: [0, 1],
          colors,
        },
      }}
      onLayout={handleLayout}
      >
      <Button
        {...buttonProps}
        p="0"
        onLayout={handleLayout}
        bg="transparent"
        colorScheme={colorScheme}
        _pressed={{ bgColor: "transparent" }}
        onPressIn={handlePressIn}
        onPressOut={handlePressOut}
      >
        {children}
      </Button>
    </Box>
  );
};
0 Answers
Related