DEV Community

Cover image for πŸ¦“ The Zebras Guide to Showcase Markdown Images in Light & Dark Mode πŸš€
Nathan Tarbert
Nathan Tarbert

Posted on • Updated on

πŸ¦“ The Zebras Guide to Showcase Markdown Images in Light & Dark Mode πŸš€

Warning: Opinions expressed may not be suitable for all audiences! πŸ˜‚

TL;DR

By the end of this article, you'll know and be able to showcase your Markdown images based on user preferenceβ€Š-β€ŠDark or Light modes.

  1. I will walk through how to add two images in a GitHub README.md - based on the selected theme, your images will properly respond.

  2. I will guide you through the process of incorporating images in Markdown and demonstrate how to make them responsive using React. 😎


Table of Contents


Do you use Light or Dark?

I don’t know about you but no matter the platform, if they have the option to switch between Light and Dark mode, well it’s no contest.

That light theme is getting switched to dark, in fact as I'm writing this of course!

Dark theme

That being said, in the rapid pace of software development, creating a seamless user experience is paramount.

Part of this experience involves accommodating user preferences, such as light and dark modes.

I can remember back a few years ago when Github announced the option for a user to switch to β€œDark Mode” and it was a pretty big deal.

GitHub dark theme

The big moment that Github reveals Dark theme 🀩

December 8, 2020 πŸŽ†

In recent years, the advent of dark and light mode options in user interfaces has become a popular trend.

I’m definitely not the only one who prefers using the dark theme option, according to Android users, 91.8% of the users prefer dark mode so we can guess the number is pretty high across all OS.

This of course can be a heated debate so I will do my best to keep my opinions to a minimum.

Light mode meme

Improving User Experience

The main goal is to improve user experience by offering options in your app.

There are several ways to create multiple versions of each image and in this tutorial we won't get into the nitty gritty.

Just make sure your images that stand out in both themes with a transparent background and you'll be golden.

Let's get the party started!

Responsive Images in Your GitHub README

Do you have a project and want to make your GitHub project README.md really pop?

This is where no matter what light theme the user is using, we will need a method to specify which theme (light or dark) an image should be displayed in Markdown.

This is particularly useful when you want to optimize the display of images based on the user's chosen color scheme, and it involves using the HTML <picture> element in combination with the prefers-color-scheme media feature shown below.

Go ahead and drag your image files directly into GitHub and place after the srcset=.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://github.com/boxyhq/.github/assets/66887028/df1c9904-df2f-4515-b403-58b14a0e9093">
  <source media="(prefers-color-scheme: light)" srcset="https://github.com/boxyhq/.github/assets/66887028/e093a466-72ea-41c6-a292-4c39a150facd">
  <img alt="BoxyHQ Banner" src="https://github.com/boxyhq/jackson/assets/66887028/b40520b7-dbce-400b-88d3-400d1c215ea1">
</picture>
Enter fullscreen mode Exit fullscreen mode

And voila!

SAML Jackson dark mode

SAML Jackson light mode

Great, do you have 5 seconds?

Please star ⭐ the SAML Jackson repo


Responsive Images in Markdown Using React

Lets say today I'm going to be writing a blog in Markdown like I normally do, and publish it to my website.

The images I use need to be responsive based on both user preferences but it's not possible in Markdown to listen for a theme change in local storage and set state.

local storage

Well thankfully there is a way to handle this dilemma if we import React into our Markdown file but lets first create a component.

React File

src/components/LightDarkToggle.js

import React, { useEffect, useState } from 'react';

function ToggleImages() {

// Define a state variable to track the user's login status
const [currentTheme, setcurrentTheme] = useState(localStorage.getItem('theme'));

// Add an event listener for the 'storage' event inside a useEffect
useEffect(() => {
  const handleStorageChange = (event) => {
    console.log('Storage event detected:', event);

    // Check the changed key and update the state accordingly
    console.log("event", event.key)
    if (event.key === 'theme') {
      setcurrentTheme(event.newValue);
    }
  };

  window.addEventListener('storage', handleStorageChange);

  // Clean up the event listener when the component unmounts
  return () => {
    window.removeEventListener('storage', handleStorageChange);
  };
}, []); // The empty dependency array ensures that this effect runs once when the component mounts

  return (
    <div className="image-container">
      {currentTheme == 'light'? (
        <img
        id="light-mode-image"
        src="/img/blog/boxyhq-banner-light-bg.png"
        alt="Light Mode Image"
        ></img>
      ):(
        <img
        id="dark-mode-image"
        src="/img/blog/boxyhq-banner-dark-bg.png"
        alt="Dark Mode Image"
        ></img>
      )}
    </div>
  );
}

export default ToggleImages;
Enter fullscreen mode Exit fullscreen mode

I've added comments and a couple console logs in the code to help walk through what's happening but lets quickly break it down.

  • The React useState hook manages the state of currentTheme, which represents the user's chosen theme stored in the local storage.

  • The useEffect hook is used to add an event listener for the 'storage' event. When the storage event occurs (indicating a change in local storage), the component checks if the changed key is theme and updates the currentTheme state accordingly.

  • The component renders different images based on the user's chosen theme, displaying a light mode image if the theme is light and a dark mode image if the theme is anything else.

Cool, lets move on!

Markdown File

Let's create a .md file for our new blog.


---
slug: light-and-dark-mode-responsive-images
title: 'Light and Dark Mode Responsive Images'
tags_disabled:
  [
    developer,
    react,
    javascript,
    open-source,
  ]
image: /img/blog/light-dark.png
author: Nathan Tarbert
author_title: "Community Engineer @BoxyHQ"
author_url: https://github.com/NathanTarbert
author_image_url: https://boxyhq.com/img/team/nathan.jpg
---

import ToggleImages from '../src/components/LightDarkToggle.js';

## 🀩 Let's start this blog off with a bang! 

Our business logo is now responsive with each user's preference, whether it's **light** or **dark** mode!


<div>
  <ToggleImages />
</div>


More blog words...
Enter fullscreen mode Exit fullscreen mode

At this point we are simply importing our React component and rendering it in our Markdown file.

Since this is a Next.js app let's fire up the server npm run dev and see the results.

cat drum roll

website dark mode

and switch over to light theme

website light mode

Lets open the console to see our events

console.log

There you have it!

Those are a couple of ways to showcase your responsive images in Markdown and one of the examples uses React to help us set the state in local storage.

I hope you liked this article and if you love developing please follow me on X (Twitter) and I'll see you next time!

Top comments (10)

Collapse
 
fernandezbaptiste profile image
Bap

Very useful!

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Thanks for the positive feedback :)

Collapse
 
annaredbond profile image
annaredbond

Ooh! Always a dark mode fan! Good thinking!

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

haha yes :)
Thanks @annaredbond!

Collapse
 
nevodavid profile image
Nevo David

Great article, Nathan!
Thank you!

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Thank you @nevodavid!

Collapse
 
arindam_1729 profile image
Arindam Majumder

Didn't know this before! Will implement it now!

Thanks for sharing!

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

You're welcome @arindam_1729.
Thanks for the great feedback.

Collapse
 
srbhr profile image
Saurabh Rai

Handy post, Nathan, Dynamic and Responsive B/W Image is what we need.

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Thanks @srbhr, yes exactly. I'm sure you see it all the time like I do, especially in GitHub README's, an image you can barely see an outline and know one is there but was only created for light :)