1

I create a Theme context for my nextjs app.

This is _app.tsx:

function App({ Component, pageProps }: AppProps) {

  return (
    <Provider store={store}>
      <WrapLayout>
          <Component {...pageProps} />
      </WrapLayout>
    </Provider>
  )
}

This is WrapLayout.tsx:

export const ThemeContext = createContext<ThemeData>({
  theme: GlobalTheme.LIGHT,
  setTheme: () => {
    //
  },
})

export const useThemeContext = () => useContext(ThemeContext)    

function WrapLayout({ children }: { children: ReactElement }) {
      const [theme, setTheme] = useState<GlobalTheme>(GlobalTheme.LIGHT)
    
      return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
          <div id="theme-layout" data-theme={theme} className="text-txt-primary">
            {children}
          </div>
        </ThemeContext.Provider>
      )
    }

The theme have 2 val: light and dark, light is default.

I have 2 routers: / and /manager

When I'm in /manager page, change theme to dark: <div id="theme-layout" data-theme='dark' className="text-txt-primary">.

Then rout to /, the context is reset: <div id="theme-layout" data-theme='light' className="text-txt-primary">

I have searched some information but not work.

How can I fix that?.

Edit:

The problem is Im using next-18n:

export async function getServerSideProps({ locale }: { locale: string }) {
  try {
    return {
      props: {
        ...(await serverSideTranslations(locale, ['common'])),
      },
    }
  } catch (error) {
    return {
      props: {
        ...(await serverSideTranslations(locale, ['common'])),
      },
    }
  }
}

If I remove i18n everything work.

kan
  • 73
  • 6

1 Answers1

0

It may not be ideal, but you can always store your theme in local storage, and each time, check if it is present, and if it is, use it.

wleklinski
  • 58
  • 4
  • Thank for ur ans. But I use `transition-duration: 300` to make the changes is softer. That mean each time `routing`, the `transition-duration` will be invoked, the page is from `light` to `dark` in 300ms, that is realy realy bad UX. – kan Jul 05 '23 at 11:00
  • Yeah, you're right. :/ – wleklinski Jul 05 '23 at 19:14