Darkmode not working on tailwind headless UI

1k Views Asked by At

Darkmode works everywhere in my react app, except on a headless ui combobox. I put a styled h1 in the same component and applied dark:bg-red-200(and any other style) no problem. The combobox accept all other tailwind utilities including attibutes like hover: but not the dark: property.

2

There are 2 best solutions below

0
On BEST ANSWER

For others (such as me) stumbling upon this:

  • E.g. the Dialog-component (and I assume others too) render right in the body tag (source)
  • If you are using "the class strategy" to handle dark mode (i.e. adding a "dark" class to the wrapper) this will be a problem, because that class is not anymore parent to the Dialog (because your wrapper is also only a child to the body)

Solution I ended up using:

I ended up using useEffect to add the dark class to the body:

useEffect(() => {
  if(darkMode){
    document.body.classList.add('dark')
  }else{
    document.body.classList.remove('dark')
  }
}, [darkMode])
0
On

VueJs Problem:

I believe this happens because the Dialog(modal) is part of the built files which are auto injected.

VueJS Solution:

I just stumbled on a similar issue with vue and fixed it by adding a similar variable i added to my App wrapper in the scoped component, :class="isDark ? 'dark' : ''" as follows:

  <Dialog
      :class="isDark ? 'dark' : ''"
      as="div"
      class="relative z-[1000]"
      @close="modalOpen = false"
    >
</Dialog>

Note that in my code isDark is a boolean variable which comes from the store. also have a watcher around it to listen to changes in theme.

 data() {
    return {
      isDark: this.$store.getters.getIsDark,
    };
  },

My watcher:

watch: {
   // whenever isDark changes, this function will run
   "$store.state.isDark": function () {
     this.isDark = this.$store.state.isDark;
   },
},

Works like charm!