Search code examples
reactjsjsonchakra-ui

How to use json values with React Chakra UI theme


So I have been trying (without success) to use values stored in a json file to override the Chakra UI theme.

My data.json file looks like this

[
  {
    “radius”: “1px”,
    “color”: “#5843F5”,
    “font”: “Arial”
  }
]

And my theme.js file looks like this

import { extendTheme } from “@chakra-ui/react”
import JsonData from ‘data.json’

export const myNewTheme = extendTheme({
 JsonData.map(item => ({
  colors: {
   primary: item.color,
   secondary: “#FF6F91”,
   highlight: “#00C9A7”
  },
 }))
});

The problems returned is as below

JS theme.js src (1)
 ‘,’ expected. ts(1005) [Ln7, Col 11]

So within JsonData.map the “.” is highlighted as an error.

Any idea what I’m doing wrong?

Thanks a lot for your help


Solution

  • It will depend on how you want to define and access your custom themes.

    In case of having many themes stored, how would you want to select each theme?

    If you want to keep an array in the json, you could add the id

    [
      {themeId: '1111', color: 'xxx'},
      {themeId: '1112', color: 'xxx'},
    ...
    ]
    

    However, I've seen more often the usage of objects for multiple themes like:

    {
      darkTheme: {primaryColor:'', font:'',...},
      lightTheme: {primaryColor:'', font:'',...},
      ...
    }
    

    Then you can access each theme JsonData['darkTheme'] or JsonData['lightTheme']

    Focusing on your code where you are only defining one theme, I can see in their docs it expects an object, but your JSON is stored inside an array

    you’d have two options:

    get the element you one from the array, something like

    const customTheme = JsonData[0];
    extendTheme({
      colors: {
      secondary: "#FF6F91",
       highlight: "#00C9A7",
       primary: customTheme.color,
      }
    })
    

    or store the theme as an object in the .json file.

    {
      "radius": "1px",
      "color": "#5843F5",
      "font": "Arial"
    }
    

    extra: to make it completely dynamic, you can use a “spread operator” to overwrite all the values that match the same name inside the theme:

    const customTheme = JsonData[0];
    extendTheme({
     colors: {
       secondary: "#FF6F91",
       highlight: "#00C9A7",
       ...customTheme
      }
    })