skip to Main Content

At present, we are having no conditions to load CSS files. So, we are importing the required .scss files statically in styles.scss file that we have. But now, we have to load different scss files(themes) in the same styles.scss file based on the data we get in session storage. Can someone help me how to do it?
Thanks in advance.

2

Answers


  1. Create separate SCSS files for each theme you want to use.

    In your JavaScript code, check the session storage for the current theme data.

    Based on the theme data in session storage, dynamically update the href attribute of the link element that references the styles.scss file to point to the appropriate theme SCSS file.

    Login or Signup to reply.
  2. You will not be able to directly load .scss files into browsers. It needs to be transpiled into .css files at runtime as .scss files are used strictly for development convenience.

    You also won’t be able to conditionally import .scss file within another .scss file depending on sessionStorage value stored in the browser.

    However, you can conditionally import different style (.css) files depending on sessionStorage values. Take at look at below example.

    const LightTheme = React.lazy(() => import('./themes/lightTheme'));
    const DarkTheme = React.lazy(() => import('./themes/darkTheme'));
    
    const ThemeSelector = ({ children }) => {
      const CHOSEN_THEME = sessionStorage.getItem('TYPE_OF_THEME') || TYPE_OF_THEME.DEFAULT;
      return (
        <>
          <React.Suspense fallback={<></>}>
            {(CHOSEN_THEME === TYPE_OF_THEME.LIGHT_MODE) && <LightTheme />}
            {(CHOSEN_THEME === TYPE_OF_THEME.DARK_MODE) && <DarkTheme />}
          </React.Suspense>
          {children}
        </>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search