javascriptreactjsreact-hookstailwind-cssdarkmode

Is there any way to change image in tailwindcss when dark mode toggled?


I was looking around, but couldn't find any related Q&A out there. I'm building a project in ReactJS with tailwindCSS, and implementing dark mode to the site. Everything works fine, but now I have some issues with a background image. I have set the two image in the tailwind.config.js

  darkMode: 'class',
  theme: {
    extend: {
      backgroundImage: (theme) => ({
        'code': "url('/src/components/About/coding-bg-dark.png')",
        'light-code': "url('/src/components/About/lightcode.png')",
       })
    },
  },

and have the classNames on the decent section

<section id='introduction' className="bg-code dark:bg-light-code bg-cover bg-fixed flex flex-wrap content-center w-full md:h-screen">

but when I toggle dark mode, the image doesn't change, the dark image stays on the light mode. Any idea how could I go around?


Solution

  • You need to add darkMode: 'media' in your tailwind.config.js, as well as extend the background image's variants to include dark mode. Here is an example tailwind.config.js:

    module.exports = {
      darkMode: 'media',
      theme: {
        extend: {
          backgroundImage: (theme) => ({
            'image-one':
              "url('https://images.unsplash.com/photo-1629651480694-edb8451b31aa?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=668&q=80')",
            'image-two':
              "url('https://images.unsplash.com/photo-1629651726230-6430554a8890?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2734&q=80')",
          }),
        },
      },
      variants: {
        extend: {
          backgroundImage: ['dark'],
        },
      },
      plugins: [],
    }
    

    Then it should work. You can see a working example here.