Implementation of dark mode with variables in React/Sass project

Viewed 863

I am working on a Sass project and I am pretty new to it.

I have a _variables.scss file which contains the variables for UI. I want to change the values of those variables dynamically (not creating new ones), with the use of React. How can I do so?

Expected Outcome is something like: In scss file, Check if dark mode is active or not and define a set of variables.

In js file, Change the state of light and dark mode programmatically.

2 Answers

Create SCSS folder and put your all the application .scss files inside there.

$themes: (
  light: (
    colorBackground: white,
    colorBackgroundBody: #f2f4f7,
    colorHeaderDataPicker:#6db0ff,
    colorText: #646777,
    colorTextAdditional: #646777,
    logoImg: url(../../shared/img/logo/oiclogo.png),
    colorHover: #fafbfe,
    colorFolderHover: #f0eeee,
    colorBorder: #eff1f5,
    colorIcon: #dddddd,
    imgInvert: invert(0%),
    colorFieldsBorder: #f2f4f7,
    colorBubble: rgba(242, 244, 247, 0.65),
    colorBubbleActive: rgba(234, 238, 255, 0.6),
    colorScrollbar: #B4BFD0,
    colorFitness: #646777,
    colorEmoji: #232329,
  ),
  dark: (
    colorBackground: #232329,
    colorBackgroundBody: #2a2a31,
    colorHeaderDataPicker:#063263,
    colorText: #dddddd,
    colorTextAdditional: #999999,
    logoImg: url(../../shared/img/logo/oiclogo.png),
    colorHover: #38373f,
    colorFolderHover: #ffffff1A,
    colorBorder: #333246,
    colorIcon: #605f7b,
    imgInvert: invert(100%),
    colorFieldsBorder: #33333a,
    colorBubble: rgba(68, 79, 97, 0.65),
    colorBubbleActive: rgba(92, 104, 156, 0.6),
    colorScrollbar: #606071,
    colorFitness: #ffffff,
    colorEmoji: #ffffff,
  )
);

Use this structure in _variables.scss file and change the property accordingly

You can use something like this:

$dark: #333
$white: #fff

@if $theme == 'dark' {
  color: $dark;
}

@if $theme == 'light' {
  color: $light;
}

This approach is described at sass lang website. You can set $theme variable as regular variable as described in example in documentation.

If you are using webpack as a module bundler and sass-loader package as sass builder, you can set $theme variable in the webpack config:

{
  loader: 'sass-loader',
  options: {
    additionalData: "$theme: 'dark';",
  },
}

Also I would highly reccomend you to read about prefered-color-scheme media querie if you will have only light and dark themes. It allows to takes into consideration users operation system defaults.

Related