How to use the NativeBase theming functionality to make different header variants?

Viewed 192

I'm trying to create a variant to scale the fontSize of Heading in NativeBase.

The following does not work.

const theme = extendTheme({
  components: {
    Heading: {
      variants: {
        h2: {
          fontSize: {
            base: 'xs',
            sm: 'xs',
            md: 'sm',
            lg: 'sm',
            xl: 'md',
          },
        },
      },
    },
  },
});

Nothing changes in...

<Heading variant="h2">Some Header Text</Heading>

What is the correct way to make a scalable Heading component?

2 Answers

So here, Variant will be resolved first and then sizes will be resolved. So fontSize from size will override fontSize from variant. You can follow the below approach to apply size to your heading.

export const Example = () => {
  const theme = extendTheme({
    components: {
      Heading: {
        sizes: {
          myCustomSize: {
            fontSize: { base: 'lg', md: '2xl', lg: '3xl' },
          },
        },
        defaultProps: {
          size: 'myCustomSize',
        },
        variants: {
          h1: {
            _light: {
              color: 'red.500',
            },
            _dark: {
              color: 'amber.500',
            },
          },
        },
      },
    },
  });

@Ankit-Taylor gets all the credit for his answer. But, I also wanted to explain exactly how I implemented his advice.

The following allows for <Heading> to scale across screen sizes and easily allows us to make smaller headers by doing <Heading size="h2"> or <Heading size="h3"> (which also scale across screen sizes).

export const Example = () => {
  const theme = extendTheme({
    components: {
      Heading: {
        defaultProps: {
          size: 'h1',
        },

        sizes: {
          h1: {
            fontSize: {
              base: 'lg',
              sm: 'xl',
              md: '2xl',
              lg: '3xl',
              xl: '4xl',
            },
          },
          h2: {
            fontSize: {
              base: 'md',
              sm: 'lg',
              md: 'xl',
              lg: '2xl',
              xl: '3xl',
            },
          },
          h3: {
            fontSize: {
              base: 'sm',
              sm: 'md',
              md: 'lg',
              lg: 'xl',
              xl: '2xl',
            },
          },
        },
      },
    },
  });
};

Related