loading...

Implement Dark / Light Mode Themes with Ionic React

chilupa profile image Pavan Chilukuri Updated on ・2 min read

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{}
}

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 {}

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');

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>

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! 😎

Posted on by:

chilupa profile

Pavan Chilukuri

@chilupa

Full Stack Developer πŸ’» Photographer πŸ“·

Discussion

markdown guide