Saturday, June 26, 2021

How to Create Custom Theme for UI using Grommet V2

 Hello,

In this blog we will understand how you can create custom theme for your using Grommet V2 in your React app.

Using Grommet v2, you can leverage the theme capabilities and define a customTheme as a JS object with your desired colors, margin padding etc. Let's see how we can do this. 

First define your custom theme as JS object. As you can see we have defined some existing grommet color like background, brand. Also we have defined our own color like custom-1, custom-2 etc and then used it in button. 

const customTheme = {

  global: {

    colors: {

      background: "#fff",

      brand: "#000",

      "custom-1": "#aaaaaa",

      "custom-2": "#bbbbbb",

      "custom-3": "#444444"

    }

  },

  button: {

    default: {

      background: "brand",

      color: "white"

    },

    primary: {

      background: "custom-1",

      color: "white"

    },

    secondary: {

      background: "custom-3",

      color: "dark-2"

    }

  }

}

For more information on theme customisation and JSON structure you can visit Official Grommet site

Now you can apply this theme to your application as below.

import { Grommet, Box } from 'grommet';

const DemoGrommet = () => (

  <Grommet theme={customTheme}>

     <Box background="custom-1" >

     </Box>

  </Grommet>

);

export default DemoGrommet;

In case you want to keep default values of Grommet theme and want to override only few things with your theme, you can use deepMerge function provided by grommet v2 utils. 

import { deepMerge } from 'grommet/utils';

import { generate } from 'grommet/themes/base';

const mergedTheme = deepMerge(generate(16), customTheme);

Here generate function generates default theme with 16 pixel font size and then it merge it with your custom theme and provide you updated theme.

No comments:

Post a Comment