Skip to content

Instantly share code, notes, and snippets.

@abdulbasetbasher
Last active September 23, 2022 18:00
Show Gist options
  • Save abdulbasetbasher/f4ea1b8068641b4f159c24e24397fdff to your computer and use it in GitHub Desktop.
Save abdulbasetbasher/f4ea1b8068641b4f159c24e24397fdff to your computer and use it in GitHub Desktop.
nuxt with chakra ui persisting the color mode - fix flashing issue too

concept of persisting chakra ui color mode in nuxt

you need to save dark mode in cookies and use nuxt store to set, get and togggle dark mode, also in template you need to set conditional chakra componet according to value of darkmode in nuxt store

modules needed:

  • cookie-universal-nuxt
nuxt with chakra ui persisting the color mode - fix flashing issue too
<!-- layouts/default.vue -->
<template>
<CThemeProvider>
<CColorModeProvider>
<component :is="isDark ? 'CDarkMode': 'CLightMode'">
<CBox font-family="body" as="main">
<CReset />
<div class="container">
<CBox v-bind="mainStyles[colorMode]" d="flex" w="100vw" h="100vh" flex-dir="column"
justify-content="center">
<NavBar />
<Nuxt keep-alive />
</CBox>
</div>
</CBox>
</component>
</CColorModeProvider>
</CThemeProvider>
</template>
<script>
import {
CDarkMode,
CLightMode
} from '@chakra-ui/vue'
import NavBar from '~/components/NavBar.vue';
export default {
name: 'DefaultLayout',
components: {
CDarkMode,
CLightMode,
NavBar
},
data () {
return {
showModal: false,
mainStyles: {
dark: {
bg: 'gray.700',
color: 'whiteAlpha.900'
},
light: {
bg: 'white',
color: 'gray.900'
}
}
}
},
computed: {
isDark() {
return this.$store.getters.getDarkMode
},
colorMode () {
return this.isDark ? 'dark' : 'light'
}
}
}
</script>
// store/index.js
export const state = () => ({
isDark: false
})
export const getters = {
getDarkMode(state) {
return state.isDark
}
}
export const mutations = {
toggleDarkMode(state) {
state.isDark = !state.isDark
},
setDarkMode(state, mode) {
state.isDark = mode
},
}
export const actions = {
nuxtServerInit({ commit }, { app }) {
commit('setDarkMode', app.$cookies.get('isDark') || false)
}
}
<!-- components/NavBar.vue -->
<template>
<CBox mb="3">
<CIconButton mr="3" :icon="colorMode === 'light' ? 'moon' : 'sun'" :aria-label="`Switch to ${
colorMode === 'light' ? 'dark' : 'light'
} mode`" @click="toggle" />
</CBox>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
name: 'NavBar',
inject: ['$chakraColorMode'],
computed: {
colorMode() {
return this.$chakraColorMode()
}
},
methods: {
toggle() {
this.$cookies.set('isDark', !this.$cookies.get('isDark'), {
path: '/',
maxAge: 60 * 60 * 24 * 7
})
this.toggleDarkMode()
},
...mapMutations({
toggleDarkMode: 'toggleDarkMode'
})
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment