🦓 The Zebras Guide to Showcase Markdown Images in Light & Dark Mode 🚀
Tags: webdev, programming, tutorial, javascript
Published: 2023-11-17 14:26:55

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?](#do-you-use-light-or-dark)
- [Improving User Experience](#improving-user-experience)
- [Responsive Images in Your GitHub README](#responsive-images-in-your-github-readme)
- [Responsive Images in Markdown Using React](#responsive-images-in-markdown-using-react)
- [React File](#react-file)
- [Markdown File](#markdown-file)

<hr />

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s0yfjc2yv5pfyacu74go.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qi10urco3o6fdojm6ipf.png)


[The big moment that Github reveals Dark theme](https://t.co/HEotvXVJ7R) 🤩

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](https://www.androidauthority.com/dark-mode-poll-results-1090716/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m3yiepj8a46rwhu69fgw.png)

## 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=`.

<br />


```javascript
<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>
```

And voila! 


![SAML Jackson dark mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q51g41fjfqnposn50una.png)


![SAML Jackson light mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d0xzs88txjylnixilaqu.png)

Great, do you have 5 seconds? 

{% cta https://github.com/boxyhq/jackson %}  Please star ⭐ the SAML Jackson repo {% endcta %}

<hr />

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrjz4to8x17h63dtybxn.png)


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

```javascript
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;
```

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.

```javascript

---
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...
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lyjzjqgcwaubyj5ve1o3.gif)



![website dark mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qraltb34mrl9y8j9jppq.png)

and switch over to light theme

![website light mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u33jgzha5fbfy6tlb4hs.png)

Lets open the console to see our events


![console.log](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpxz5gbhwt308vatsnkp.png)

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)](https://twitter.com/nathan_tarbert) and I'll see you next time!