Toggling Light/Dark theme programmatically API 4.x

1343
4
Jump to solution
12-10-2021 07:50 AM
RichardMoussopo
Occasional Contributor III

The API provides two different css files for light and dark theme. I am trying to figure out a better way of switching theme on toggle button click. I've tried unloading the light css file then load the dark css file and I am not impressed with this approach. Does anybody out there ever tried this?

Thank you

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
ReneRubalcava
Frequent Contributor

I don't know how you're updating it, but you can just update the href of the link tag.

 

let theme = "dark";
btn.addEventListener("click", () => {
    if (theme === "light") {
      sheet.href = "https://js.arcgis.com/4.22/esri/themes/dark/main.css";
      theme = "dark";
    } else if (theme === "dark") {
      sheet.href = "https://js.arcgis.com/4.22/esri/themes/light/main.css";
      theme = "light";
    }
});

 

https://codepen.io/odoe/pen/qBPaPpR?editors=1000

View solution in original post

4 Replies
ReneRubalcava
Frequent Contributor

I don't know how you're updating it, but you can just update the href of the link tag.

 

let theme = "dark";
btn.addEventListener("click", () => {
    if (theme === "light") {
      sheet.href = "https://js.arcgis.com/4.22/esri/themes/dark/main.css";
      theme = "dark";
    } else if (theme === "dark") {
      sheet.href = "https://js.arcgis.com/4.22/esri/themes/light/main.css";
      theme = "light";
    }
});

 

https://codepen.io/odoe/pen/qBPaPpR?editors=1000

RichardMoussopo
Occasional Contributor III

Thank you Rene, I am using React but this did the trick. I really appreciated

0 Kudos
René_Ténière
Occasional Contributor

René,

How do you listen for changes to the theme? I have developed a widget and would like to listen for the theme changes for the internal CSS.

Thanks,

René T.

0 Kudos
LindaCecilieKjeldsen
New Contributor

This seems to no longer function for the popup? It seems "something" happened around version 4.25..? It is possible to make the popup light if you import light stylesheet, and dark if you import dark. But if you switch in runtime, nothing happens in the popup.

0 Kudos