DEV Community

Pavan Chilukuri
Pavan Chilukuri

Posted on • Updated on

Implement Dark / Light Mode Themes with Ionic React

Light Mode vs Dark Mode

It has become a standard nowadays to have both light mode and dark mode themes in almost any of the web or mobile applications.

Assuming you already have the initial setup for React app using Ionic CLI.

Believe me or not! This implementation won't take more than 5 minutes and can be completed if you follow these two steps.

  1. CSS Changes
  2. Component Changes

This post will be useful to you if you are implementing an Ionic 5 app using React. Even if you are using Angular or any other framework, the syntax might differ but underlying logic and implementation should be the same.

CSS Changes

Go straight to the theme/variables.css file and remove the css media query @media (prefers-color-scheme: dark) query which sets the app to the system's theme settings. Meaning, it will set the app theme based on your Apple or Android mobile device theme settings.

Initially, your variable.css file should look something like this.

:root {}

@media (prefers-color-scheme: dark) {
  body{}

  .ios .body{}

  .md .body{}
}

Enter fullscreen mode Exit fullscreen mode

Like I mentioned, you will have to remove the css media query. Now, your theme/variables.css file format should look like this.

:root {}

body.dark {}

.ios .body.dark {}

.md .body.dark {}
Enter fullscreen mode Exit fullscreen mode

Component Changes

Coming to the implementation of the toggle button on UI,
let's set up a switch ( a simple function 😉 ) which will handle the toggling between light and dark modes.

const toggleDarkModeHandler = () => document.body.classList.toggle('dark');
Enter fullscreen mode Exit fullscreen mode

In your functional component, let's create the switch, a toggle button and pass in the handler that we wrote to onIonChange property.

<IonList>
  <IonItem lines="none">
    <IonIcon slot="start" icon={moon} />
    <IonLabel>Dark Mode</IonLabel>
    <IonToggle slot="end" name="darkMode" onIonChange={toggleDarkModeHandler} />
  </IonItem>
</IonList>
Enter fullscreen mode Exit fullscreen mode

That's it! You are all set to lift off! 🚀
Now that your handler and the toggle button are in place, clicking on the toggle button should switch between light and dark mode themes on the fly!

I also created a working example using CodeSandbox. Feel free to explore the source code and do comment if you have any question or thoughts. Thank you for your time reading my post.

Happy Coding! 😎

Top comments (1)

Collapse
 
muringemuthoni profile image
Aurora

Thank you so much