Toggling Light/Dark theme programmatically API 4.x

419
3
Jump to solution
12-10-2021 07:50 AM
RichardMoussopo
Occasional Contributor II

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 II

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

3 Replies
ReneRubalcava
Frequent Contributor II

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 II

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

0 Kudos
RenéTénière
New Contributor III

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