Creating Dark theme using React hooks and context in Material UI
In this article, I will be showing you, how we can use React hooks and context to create dark theme in Material ui
What is Context?
In a typical React application, we can share data between components using props, however, As the application grows, and new components are added this method for sharing data between components becomes complex, and hard to manage.
To solve this problem React introduced Context. Context provides a way through which we can share data between components, without having to pass props to each component manually.
Creating the application
Open up the terminal and create a new react app, by using the following commands-
npx create-react-app myapp
cd myapp
yarn start
This will start the local react development server at http://localhost:3000
Installing the dependencies
install material ui using
yarn add @material-ui/core
yarn add @material-ui/icons
Creating the themes
Under the src folder create a new JavaScript file, called theme.js and paste the following code in it-
Creating the Theme context
under the src folder create a new folder, hooks, inside this folder create a new JavaScript file, themeContext.js
This file will store all the code for managing the current theme.
Now paste the following the code in the themeContext.js file
Now open up the index.js file, and paste the following code-
Now, to toggle the theme, We can create a Navbar component inside App.js and then, call the handleDarkMode function inside the Navbar.
Below is a gif, of how the final application looks
And that’s it, Hope you have a great day ahead!!