Is it possible to override the theme sizes of NativeBase to obtain rem units?

479 Views Asked by At

I'm new to NativeBase and I'm overriding the default theme to obtain a custom one where I would like to use rem units. I'm using the extendTheme function as described in the docs:

const myCustomTheme = extendTheme({
  sizes: {
    0: 0,
    1: 16,
    2: 32,
    // and so on
  }
})

However, if I try to use it in an element, the sizing stays the same.

At the moment I created a workaround by using a function to mimic the same effect:

const rem = (r: number) => `${r * 16}px`

So I can

<Button mb={rem(2)}>My Button</Button>

But this is not very nice to use.

Do you know how could I use rem units in a similar way without requiring this function, with a syntax like this

<Button mb={2}>My Button</Button>

or even better like this

<Button mb="2rem">My Button</Button>

that uses rem units?

I tested this only using the iOS simulator, so I don't know if it would have worked worked differently on Android or Web.

Original theme index.ts, sizes.ts and space.ts.

1

There are 1 best solutions below

1
On

So I don't see this in any documentation, but the key you want to use to override (or add to) sizes is actually space and not sizes. I found this by going through the NativeBase theme source on GitHub.

const myCustomTheme = extendTheme({
  space: {
    '0': 0, // NB use string keys... not sure if that matters.
    '1': 16,
    '2': 32,
    // and so on
  }
})

As for the rem question, you could add 2rem as a custom size/space, but it would not run your function. So if you wanted something like 1.5rem, it would have to be "hard coded" as far as I can tell.

You could go the code generated route if you have/need a lot of options:

/** 
 * Generates 10 sizes at every 0.5rem
 * Change Array(x) to customize the number of sizes.
 * For larger/smaller steps, change the factor of idx (idx/2)
 **/
space: {
  '0': 0,
  '1rem': 16,
  '2rem': 32,
  // or...
  ...Array.from(Array(10).keys()).reduce((acc, _itm, idx) => {
    if (idx === 0) return acc;
    acc[`${idx/2}rem`] = idx / 2 * 8;
    return acc;
  }, {}),
},