Mark Johnson

    Building this site: Part 3 - Adding dark mode

    Sunday 24th May, 2020 - 2 min read

    I wanted to add dark mode to the site, and after a quick search I found an excellent write-up by Josh Comeau on The Quest for the Perfect Dark Mode. I hadn’t realised until reading his post how tricky dark mode can be, and I’m grateful that he had tackled the difficulties and I was able to stand on his shoulders. I cloned the repo built it, and then copied the code into my site.

    The dark mode implementation worked seemlessly, but the default colours needed some work and I found I had a lot of hardcoded color and background-color elements across .css and .jsx files in my site. The refactor took a couple of hours to centralise definitions and reduce the number of colour combinations being used, not aided by frequent rebuilds and the hot-reloaded didn’t seem to play nice with server side rendering.

    Once this was done, the final thing was to customise the UI for enabling and disabling dark mode.

    Light Dark

    I hid the checkbox with display: 'none' and replaced the text with FontAwesome icons for the Sun and Moon.

    import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
    import { faMoon } from '@fortawesome/free-solid-svg-icons'
    
    let icon;
    if (colorMode === 'dark') {
    icon = <FontAwesomeIcon icon={faSun} size={"lg"} className="darkModeIcon" />
    } else {
    icon = <FontAwesomeIcon icon={faMoon} size={"lg"} className="darkModeIcon" />
    }
    
    return (
    <label>
        <input 
        style={{ display: 'none' }} 
        type="checkbox"
        checked={colorMode === 'dark'}
        onChange={ev => {
            setColorMode(ev.target.checked ? 'dark' : 'light');
        }}
        />{' '}
        {icon}
    </label>
    );

    I now had the following icons

    New Light New Dark

    But because the checkbox had been removed it now wasn’t clear that the icon was clickable. To try and address this I added styling to the hover: .darkModeIcon:hover { color: var(--color-gray500); }'

    Light Hover Dark Hover

    Dark mode was now complete. A huge thanks to Josh Comeau, his MVP on GitHub was such a joy to work with. It’s rare a code sample is truly minimal, but his repo left no fluff and it made implementing this so much easier.

    Read more

    Click here to see an overview of all web-dev articles related to this site.


    Enjoyed this post? ❤️

    Subscribe by email or RSS.



    Contact