Usman Kiani
Usman Kiani

Reputation: 25

Want to load the light or dark theme based on user Choice

This is style.scss file in React CoreUI. manually commenting one of the theme style import works fine. I want to automate this theme switch by user choice.

// If you want to override variables do it here
@import "variables";

// Import styles with default layout.
// If you are going to use dark layout please comment next line
@import "@coreui/coreui-pro/scss/coreui";
// Import styles with dark layout

// If you want to use dark layout uncomment next line
//@import "@coreui/coreui-pro/scss/themes/dark/coreui-dark";

// Temp fix for reactstrap
@import "@coreui/coreui-pro/scss/_dropdown-menu-right.scss";

// If you want to add something do it here
@import "custom";

// ie fixes
@import "ie-fix";

I tried this by making two different respective style files but this solution doesnot work in Production environment.


    if (cookies.get('theme') === 'DARK_MODE'){
      require('./scss/style_dark.css');
    } else if (cookies.get('theme') === 'LIGHT_MODE'){
      require('./scss/style.css');
    }else{
      require('./scss/style_dark.css');
    }

Please guide and increase my knowledge.

Upvotes: 0

Views: 1420

Answers (1)

Paweł Qba
Paweł Qba

Reputation: 11

Add

onclick="toggleLayoutTheme()"

to your toggler:

<button class="c-header-nav-btn" type="button" title="Toggle Light/Dark Mode" onclick="toggleLayoutTheme()">
      <svg class="c-icon c-d-dark-none">
        <use xlink:href="{{ url('/icons/sprites/free.svg#cil-moon') }}"></use>
      </svg>
      <svg class="c-icon c-d-default-none">
        <use xlink:href="{{ url('/icons/sprites/free.svg#cil-sun') }}"></use>
      </svg>
    </button>

and after </body>:

<script>
  function toggleLayoutTheme() {
      if (document.body.classList.contains('c-dark-theme')) {
          document.body.classList.remove('c-dark-theme');
          localStorage.setItem('LayoutTheme', 'light');
      } else {
          document.body.classList.add('c-dark-theme');
          localStorage.setItem('LayoutTheme', 'dark');
      }
  }

function loadLayoutTheme() {
  if (localStorage.getItem('LayoutTheme') == 'dark') {
      document.body.classList.add('c-dark-theme');
  } else {
      localStorage.setItem('LayoutTheme', 'light');
  }
} loadLayoutTheme();
</script>

Upvotes: 1

Related Questions