Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 11, 2021 07:20 am GMT

Learning to toggle Dark Mode through React Hooks

I recently revisited a project of mine and found a feature that I think I can recreate with the use of React Hooks.

My current goal is to try out things from React to deepen my familiarity of it and maybe others can relate or give tips to #codenewbies like myself about React Hooks. So if you have any resource suggestions, feel free to drop them in the comments below!

So for starters..

The app that I mentioned is called SplashGlam. It is powered by ReactJS and hosted through Heroku. Feel free to toggle the day and night mode using the button on the top navigator to see what are we working with.

On Day/Bright mode..
Day mode

On Night/Dark mode..
Night mode

I also have discussed how I built the toggling feature using LocalStorage on my other blog.(What is LocalStorage?) This time around, I wanted to try Hooks to recreate at least the toggling part.

I created a repo to test things out and feel free to check it out if you wanted to test it out on your own. Github repo

Small breakdown of my code:

First

JSX for DOM elements-So I built the elements on the page first with the corresponding attributes needed like an onClick eventListener.

Second

Function snapshot-Here's how I incorporate useState in the toggle & using a function that has an if statement to trigger changes.

Third

CSS! Now that we have our functions and elements all set. Remember our function has a line of code where we change/replace the className of the body from dayMode to nightMode?

Here's my corresponding CSS to see DOM change!
CSS snapshot

Results!

Day Mode

Night Mode

And that is pretty much it! I hope anyone that needs an example in using hooks to toggle day/night mode find this helpful!

Let me know if I missed anything in the comments please! Until the next!


Original Link: https://dev.to/tolentinoel/learning-to-toggle-dark-mode-through-react-hooks-43l1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To