Dark Mode&Light Mode: Next.js with next-themes and Sass

Arda Kurt
3 min readDec 1, 2021

Hey there! It’s Arda, Junior Frontend Developer. I am building portfolio projects with React. It’s my very first medium 🎺.

New Challenge: DevJobs Listing App from frontendmentor.io

I decided to use Next.js instead of create-react-app this time. It’s a recommendation from my very new but amazing developer friend — Didem @DidemKkkaraasl1. Also, I wanted to use Sass for my new portfolio project. I like styled-components. It’s a very agile tool for frontend development. Why I decided to use Sass? No specific reason just an experimental.

The first problem on my road: Dark & Light Theme

It’s not a big problem. But I didn’t know anything about how I can manage the theme with Sass and Next.js. I am not a new player of the Sass era but I am a very new Next.js framework. Then I started to google. It’s really hard to find solution. I find two different paths but the first one is very complex for me, at the beginning. I just need a very pure and simple solution.

next-themes package is lifesaver

I just find the next-themes package from Github. All recommendation is for useTheme hook and styled components and CSS. It was a very good opportunity, I couldn’t find a direct solution. In that case, I need to tweak my file structure.

I move all theme options and variables same file.

_variables.scss to abstract/_theme.scss

SASS File Tree
Sass Theme and useTheme() hook

I just moved all theme variables and :root color options same file. Then useTheme() hook provided from next-themes. And I just add two different buttons for testing purposes.

Using ThemeProvider & Local Storage

We need to wrap our application with our ThemeProvider. I added ThemeProvider _app.js file for this project. We feed ThemeProvider with enableSystem for activating browsers prefers-color-scheme. Also, we can use storageKey for using localStorage very easily.

And 🎉 it works!

next-themes: https://www.npmjs.com/package/next-themes

project Github: https://github.com/to-arda-kurt/devjobs-app (ongoing) 🎉

Thanks for bearing with me. 👋 All the best.

--

--