Search Here

How to switch between dark modes in react js using localstorage

How to Switch between Dark Modes in React JS using LocalStorage

Dark mode provides better visibility to the user and also reduces stress on eye-sight. And in this post, I’ll show you how you can Switch between Dark Modes in React JS using LocalStorage.
We’ll be using localstorage to store the class name and when the toggle button is clicked I’ll call a function that will toggle between dark and light mode.

I’ll start with src\App.js

import React, { useEffect, useState } from 'react'
import theme_styles from './themes.module.css'
import './App.css'

function App() {

    const [ list, setList ] = useState( [] )

    useEffect( ( ) => {
        applyTheme()
        fetchGallery()
    } )

    const getTheme = () => {
        let theme = localStorage.getItem("theme")

        if( theme === "theme-light" ){
            theme = "theme-light"
        } else {
            theme = "theme-dark"
        }

        return theme
    }

    const setTheme = ( theme ) => {
        localStorage.setItem("theme", theme)
    }

    const applyTheme = (  ) => {
        let theme = getTheme()
        let body = document.getElementsByTagName('body')[0]
        
        if( theme === "theme-light" ){
            body.classList.remove( theme_styles["theme-dark"] )
            body.classList.add( theme_styles["theme-light"] )
        } else {
            body.classList.remove( theme_styles["theme-light"] )
            body.classList.add( theme_styles["theme-dark"] )
        }    
    }

    const fetchGallery = async( ) => {
        let url = `http://jsonplaceholder.typicode.com/photos`
        let res = await fetch( url )
        res = await res.json()

        if( res.length ){
            setList([...res])
        }

    }

    const toggleMode = ( ) => {
        let theme = getTheme()
    
        if( theme === "theme-light" ){
            theme = "theme-dark"
        } else {
            theme = "theme-light"
        }
        
        setTheme( theme )
        applyTheme( theme )
    }


    return (
        <>

            <div className="container"  >
                <h1 className="text-center"  >Gallery | <button onClick={toggleMode} type="button">Toggle Theme</button></h1>

                <div className="gallery-wrapper" >
                    {
                        ( list.length )
                            ? list.map( (item, index) => {

                                    return (
                                        <div key={index} className="item"  >
                                        <div>
                                            <img src={item["url"]} className="img" alt="" />
                                        </div>
                                        <p>{ item.title }</p>
                                        </div>
                                    )
                                })
                            : (
                                <p>Please wait...</p>
                            )
                    
                    }
                </div>
            </div>

        </>
    )

}

export default App;   

The ./themes.module.css consists of the CSS for light and dark mode. The function getTheme() will return the theme name. The theme class is set by calling setTheme() function and the value of the current theme is stored in localStorage.setItem("theme", theme).

Next, to apply the theme class we will have to set the current theme to HTML body tag and remove the other class which has been previously added. The applyTheme() function is called after the component App is loaded. For test gallery data I’ll be using jsonplaceholder to fetch photos for the gallery.

In src\themes.module.css

.theme-dark{
    background: #000;
    transition: background 0.5s;
}

.theme-dark h1,
.theme-dark p{
    color: #fff;
}

.theme-light{
    background: #fffefe;
    transition: background 0.5s;
}

.theme-light h1,
.theme-light p{
    color: #000;
}

The theme.module.css contains classes for all the different modes. You can also add transition a property to show the change and apply the effect to a new theme.

You can also check out other related posts on React JS Form Validation Using Formik useFormik Hook and Yup Package

In src\App.css

.container{
    width:80%;
    margin:auto;
}

.text-center{
    text-align:center;
}

.gallery-wrapper{
    display : grid;
    grid-template-columns : repeat(3,1fr);
    grid-auto-rows: 300px;
}

.gallery-wrapper .item{
    border : 1px solid #eee;
    padding : 10px 5px;
}

.img{
    width : 100%;
    height : 200px;
    object-fit : contain;
}

Here we’ll be arranging the gallery interface.

Output

final output of How to switch between dark modes in react js using localstorage

Watch Video

Here is the link to the Github repository.

Summary
Review Date
Reviewed Item
How to Switch between Dark Modes in React JS using LocalStorage
Author Rating
51star1star1star1star1star
Software Name
React JS
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development