Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1801

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T11:31:09+00:00 2024-11-25T11:31:09+00:00

Tailwind CSS and useDarkMode hook

  • 62k

Background

I've been using tailwindcss for a couple of years now. Version 2 includes the option to easily add dark mode. I thought I'd give it a try on my blog which is built using Next.js

Setup

To begin I'll assume you have a react based website with tailwindcss already set up. In the tailwind.config.js file add a darkMode option:

// tailwind.config.js module.exports = {   darkMode: 'class', // can also be set to 'media'   // ... } 
Enter fullscreen mode Exit fullscreen mode

Now when adding your styles add a dark variant alongside the 'light' styles:

<div class="bg-white dark:bg-gray-800">   <h1 class="text-gray-900 dark:text-white">Dark mode is here!</h1>   <p class="text-gray-600 dark:text-gray-300">     Lorem ipsum...   </p> </div> 
Enter fullscreen mode Exit fullscreen mode

If the .dark class is present earlier in the html tree then the dark theme will be applied.

useDarkMode Hook

For activiating the .dark class, I'm using the excellent useDarkMode hook by Donavon West which you'll need to install:

npm i use-dark-mode 
Enter fullscreen mode Exit fullscreen mode

The plugin works by toggling a class added to the body element (or a different element if specified):

body.light-mode {   background-color: #fff;   color: #333;   transition: background-color 0.3s ease; } body.dark-mode {   background-color: #1a1919;   color: #999; } 
Enter fullscreen mode Exit fullscreen mode

However, as mentioned previously tailwindcss applies the dark mode if there is a .dark class, therefore, the default classes will need to be overridden by passing the options to the useDarkMode hook:

const { toggle, value } = useDarkMode(initialState, {     classNameDark: 'dark',     classNameLight: 'light',   }); 
Enter fullscreen mode Exit fullscreen mode

And thats it unless you are using the tailwindcss typography plugin.

tailwindcss typgraphy

As my blog content is taken Markdown files I'm using the tailwindcss typography plugin to add typograhic styles to my content. This is done by adding a .prose class to the content wrapper element:

<article class="prose">   {{ markdown }} </article> 
Enter fullscreen mode Exit fullscreen mode

For the dark theme:

<article class="prose prose-dark">   {{ markdown }} </article> 
Enter fullscreen mode Exit fullscreen mode

For the blog content I would check the value returned and apply the classes accordingly:

const BlogDetails = () => {   const { darkMode } = useTheme();    return (     <AppShell>       <NextSeo title={`${title} | dlw`} description={snippet} />       <Container>         <MDXProvider components={mdxComponents}>           <article className={`${darkMode ? 'prose prose-dark' : 'prose'}`}>{children}</article>         </MDXProvider>       </Container>     </AppShell>   ); };  export default BlogDetails; 
Enter fullscreen mode Exit fullscreen mode

The issue I ran into was the .dark class would be applied by the hook but the value available when setting the .prose value could be out of sync resulting in unreadable text:

tailwindcss-dark-mode-issue

My solution was to wrap the useDarkMode hook in my own custom hook:

import { useEffect } from 'react'; import useDarkMode from 'use-dark-mode';  export const useTheme = (initialState = false) => {   const { toggle, value } = useDarkMode(initialState, {     classNameDark: 'dark',     classNameLight: 'light',   });    useEffect(() => {     const proseEl = document.querySelector('article.prose');      if (!proseEl) {       return;     }      if (value) {       document?.querySelector('article.prose').classList.add('prose-dark');     } else {       document?.querySelector('article.prose').classList.remove('prose-dark');     }   }, [value]);    return { toggle, darkMode: value }; }; 
Enter fullscreen mode Exit fullscreen mode

The hook listens for any changes to the dark mode and adds or removes the .prose-dark class as required. With the hook running on every page I escape the useEffect if the required HTML element isn't present.

javascriptreacttailwindcsswebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.