Theming Made Easy… With Context API And Local Storage
One things I always wanted to implement in my personal projects was theming but I never learnt how until very recently and it’s quite easy. In this post I’ll walk you through it step by step, the only prerequisite is some basic react knowledge.
let’s start by creating a new react app
npx create-react-app theming
and downloading bootstrap
cd themingnpm i bootstrap
importing bootstrap in the index.js and clearing default styles in our index.css
Next let’s move to our App.js, we will return a simple component that show hello world in center of the screen and apply our coloring through css variables
Next we create our themes and store, our themes will be a simple object with a name and color keys, I’ll put it an assets folder in src directory ,the themes file will look like this
Next we’ll create our store, I’ll put the store in a new context folder in the src directory, the store will have a state variable to hold into our current theme and a function to change our theme, then we’ll provide our store to the app
Next is consuming that
selectedTheme we got from our context store, but I want to create a navbar first so I can change my theme with
changeTheme I’ll add a new components folder in the src directory which will hold our Navbar.
I’ll use the default bootstrap navbar and edit it so I’ll only have the dropdown on the right side instead of the default form, I’ll also add some css to make it override the look of the default dropdown and provide my
var( — text-color) to the navbar
Our navbar expects to get
changeTheme (to change the value in context state)as props so let’s provide them our navbar and provide the navbar to our app component
Lastly the logic to apply the theming
Here’s what the extra lines of code does:
First I added a boolean and called it
isFirstRun to check if this is the first time our component is rendered to the user, the
useEffect will be executed after our component renders on the screen.
I get a value stored on the local storage (typically you won’t have this value if this is your first time ever using the app) and I find the last theme the user had based on it.
So if you had used this app before and this is the first time the component renders on your screen, I change
false, I change the default theme I get from the context with the last theme the user lastly had, and I override the value of my
var( — text-color) with the color from my
storedTheme else which runs whenever the user change the theme, I’ll change the the
var( — text-color) with the new color I’m getting from the context and save that object’s name to the local storage. this way on the next run of this app, they’ll have that last theme they had previously.
Hope you find this tutorial useful, please feel free to leave a comment if you had any question.
You can find a repo with all the code from this tutorial here: https://github.com/mazenadel19/Themeing-With-Context-Api
And you see a live version here: