{"id":2263,"date":"2022-01-25T18:21:17","date_gmt":"2022-01-25T18:21:17","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=2263"},"modified":"2022-01-25T18:21:17","modified_gmt":"2022-01-25T18:21:17","slug":"dark-mode-using-react","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=2263","title":{"rendered":"Dark Mode Using React"},"content":{"rendered":"\n<h2>Dark mode is a common feature to see on modern websites, here&#8217;s how to make your own with React.<\/h2>\n\n\n\n<!--more-->\n\n\n\n<h3><a href=\"https:\/\/dev.to\/lrth06\/dark-mode-using-react-279p#looks-cool-but-why\"><\/a>Looks Cool, But Why?<\/h3>\n\n\n\n<p>If you&#8217;ve ever worked in front of a screen, you probably know how it feels to finally get away from the computer, only to have your eyes strained over the course of the day. One way developers have started to combat this is the use of dark mode. Dark mode uses light text on a dark background, also leading to lower power consumption on certain devices. This is also a great tool in keeping users engaged and interested in your content.<\/p>\n\n\n\n<h3><a href=\"https:\/\/dev.to\/lrth06\/dark-mode-using-react-279p#creating-a-react-app\"><\/a>Creating a React App<\/h3>\n\n\n\n<p>First, we need to create a react app. The most popular way to do this is to run the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-react-app dark-mode-example\n<\/code><\/pre>\n\n\n\n<p>This will create a directory called&nbsp;<code>dark-mode-example<\/code>, and will install React and the necessary dependencies to get you started. Once that is complete, you should see the following in the terminal:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Success! Created dark-mode-example at \/home\/example\/dark-mode-example\nInside that directory, you can run several commands:\n\n  npm start\n    Starts the development server.\n\n  npm run build\n    Bundles the app into static files for production.\n\n  npm test\n    Starts the test runner.\n\n  npm run eject\n    Removes this tool and copies build dependencies, configuration files\n    and scripts into the app directory. If you do this, you can\u2019t go back!\n\nWe suggest that you begin by typing:\n\n  cd dark-mode-example\n  npm start\n\nHappy hacking!\n<\/code><\/pre>\n\n\n\n<h3><a href=\"https:\/\/dev.to\/lrth06\/dark-mode-using-react-279p#verifying-installation\"><\/a>Verifying Installation<\/h3>\n\n\n\n<p>Now that our React app is set up, lets run&nbsp;<code>cd dark-mode-example<\/code>&nbsp;and&nbsp;<code>npm start<\/code>&nbsp;to start the development server. A Browser window will open in your default browser, and you should see the following:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"https:\/\/res.cloudinary.com\/practicaldev\/image\/fetch\/s--2vtA5mt_--\/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880\/https:\/\/storage.googleapis.com\/tobyhagan_post_images\/create-react-app.webp\"><img src=\"https:\/\/res.cloudinary.com\/practicaldev\/image\/fetch\/s--2vtA5mt_--\/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880\/https:\/\/storage.googleapis.com\/tobyhagan_post_images\/create-react-app.webp\" alt=\"Default create-react-app template\"\/><\/a><\/figure>\n\n\n\n<p>Now we can open our favorite text editor and start coding. I recommend using VS Code, so we can stop our development server with&nbsp;<code>ctrl + c<\/code>&nbsp;and then run&nbsp;<code>code .<\/code>&nbsp;since we&#8217;re already in the project directory. For the purposes of this tutorial, we&#8217;ll only be editing two files:&nbsp;<code>src\/App.js<\/code>&nbsp;and&nbsp;<code>src\/App.css<\/code>. We can start by editing&nbsp;<code>src\/App.js<\/code>:<\/p>\n\n\n\n<p>It should currently look something like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import logo from \".\/logo.svg\";\nimport \".\/App.css\";\n\nfunction App() {\n  return (\n    &lt;div className=\"App\"&gt;\n      &lt;header className=\"App-header\"&gt;\n        &lt;img src={logo} className=\"App-logo\" alt=\"logo\" \/&gt;\n        &lt;p&gt;\n          Edit &lt;code&gt;src\/App.js&lt;\/code&gt; and save to reload.\n        &lt;\/p&gt;\n        &lt;a\n          className=\"App-link\"\n          href=\"https:\/\/reactjs.org\"\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n        &gt;\n          Learn React\n        &lt;\/a&gt;\n      &lt;\/header&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport default App;\n<\/code><\/pre>\n\n\n\n<p>Remove the header tag and everything within, only leaving the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import \".\/App.css\";\n\nfunction App() {\n  return &lt;div className=\"App\"&gt;&lt;\/div&gt;;\n}\n\nexport default App;\n<\/code><\/pre>\n\n\n\n<p>Now we can edit&nbsp;<code>src\/App.css<\/code>. It should currently contain the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>.App {\n  text-align: center;\n}\n\n.App-logo {\n  height: 40vmin;\n  pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .App-logo {\n    animation: App-logo-spin infinite 20s linear;\n  }\n}\n\n.App-header {\n  background-color: #282c34;\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  font-size: calc(10px + 2vmin);\n  color: white;\n}\n\n.App-link {\n  color: #61dafb;\n}\n\n@keyframes App-logo-spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n<\/code><\/pre>\n\n\n\n<p>We removed almost everything that relies on this file in the previous step, so remove everything except the&nbsp;<code>.App<\/code>&nbsp;class. The file should now look like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>.App {\n  text-align: center;\n}\n<\/code><\/pre>\n\n\n\n<p>While we have this file open, lets update the&nbsp;<code>.App<\/code>&nbsp;class, and add a few more classes we&#8217;ll use in the following steps:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>* {\n  margin: 0;\n  padding: 0;\n  box-sizing: border-box;\n}\n.App {\n  height: 100vh;\n  width: auto;\n  text-align: center;\n  font-size: 5em;\n  color: #2e3440;\n  background-color: #d8dee9;\n  transition: all 0.2s ease;\n}\n.dark,\n.dark .App {\n  color: #d8dee9;\n  background-color: #2e3440;\n  transition: all 0.2s ease;\n}\n<\/code><\/pre>\n\n\n\n<p>Lets talk about what we&#8217;ve done here. The first change you may notice is the&nbsp;<code>*<\/code>&nbsp;selector. This is a universal selector, and will apply to all elements. This serves as a simple way to reset the default styles of all elements, creating a consistent look and feel across multiple browsers. We also added a new class called&nbsp;<code>.dark<\/code>. This class will be added to the&nbsp;<code>.App<\/code>&nbsp;class when the user clicks the dark mode button. The new styles will be applied, and any elements that are not in the&nbsp;<code>.dark<\/code>&nbsp;class will not be affected.<\/p>\n\n\n\n<h3><a href=\"https:\/\/dev.to\/lrth06\/dark-mode-using-react-279p#making-a-dark-mode-button\"><\/a>Making a Dark Mode Button<\/h3>\n\n\n\n<p>Lets go back to&nbsp;<code>src\/App.js<\/code>&nbsp;and add some text, and a button to toggle dark mode on and off. We&#8217;ll assign the class&nbsp;<code>.dark-mode-toggle<\/code>&nbsp;to the button, and use the&nbsp;<code>onClick<\/code>&nbsp;event to toggle Dark Mode on and off. Because we&#8217;re using&nbsp;<code>useState<\/code>&nbsp;to toggle Dark Mode, we&#8217;ll import it at the top of the filee. Then we need to create our&nbsp;<code>darkMode<\/code>&nbsp;variable and setDarkMode modifier. For the time being we will default to&nbsp;<code>false<\/code>, which means the app will use light mode.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import \".\/App.css\";\nimport { useState } from \"react\";\n\nfunction App() {\n  const &#91;darkMode, setDarkMode] = useState(false);\n\n  return (\n    &lt;div className=\"App\"&gt;\n      &lt;h1&gt;{darkMode ? \"Dark Mode\" : \"Light Mode\"}&lt;\/h1&gt;\n      &lt;p&gt;This is a test&lt;\/p&gt;\n      &lt;button\n        className=\"dark-mode-toggle\"\n        onClick={() =&gt; {\n          setDarkMode(!darkMode);\n        }}\n      &gt;\n        {darkMode ? \"Dark Mode\" : \"Light Mode\"}\n      &lt;\/button&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport default App;\n<\/code><\/pre>\n\n\n\n<p>Once you&#8217;ve added the button, you can test it by clicking it. You should see the following:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"https:\/\/res.cloudinary.com\/practicaldev\/image\/fetch\/s--lSpDphNj--\/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880\/https:\/\/storage.googleapis.com\/tobyhagan_post_images\/light-mode-tutorial.webp\"><img src=\"https:\/\/res.cloudinary.com\/practicaldev\/image\/fetch\/s--lSpDphNj--\/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880\/https:\/\/storage.googleapis.com\/tobyhagan_post_images\/light-mode-tutorial.webp\" alt=\"Light Mode Tutorial\"\/><\/a><\/figure>\n\n\n\n<p>Click the button and the header and button text should be updated to say&nbsp;<code>Dark Mode<\/code>, thanks to the ternary statements we just implemented. Here&#8217;s what you should see after clicking the button:<br><a href=\"https:\/\/res.cloudinary.com\/practicaldev\/image\/fetch\/s--CURcHZci--\/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880\/https:\/\/storage.googleapis.com\/tobyhagan_post_images\/dark-mode-tutorial.webp\"><\/a><\/p>\n\n\n\n<h3><a href=\"https:\/\/dev.to\/lrth06\/dark-mode-using-react-279p#make-it-do-something\"><\/a>Make it do something<\/h3>\n\n\n\n<p>Awesome! We&#8217;re toggling dark mode on and off with a button, but we&#8217;re not changing any styling yet. To do this, we&#8217;ll need to import&nbsp;<code>useEffect<\/code>&nbsp;alongside our existing&nbsp;<code>useState<\/code>&nbsp;hook. After importing&nbsp;<code>useEffect<\/code>, we can use it below our variable declarations. When using&nbsp;<code>useEffect<\/code>, we can pass in a function as the second argument. This function will be called after the component mounts, and will be called again whenever the&nbsp;<code>darkMode<\/code>&nbsp;variable changes. If the second argument is an empty function, then the effect will only run once when the component mounts. We can use this to add a listener to the&nbsp;<code>darkMode<\/code>&nbsp;variable, and then add or remove the&nbsp;<code>.dark<\/code>&nbsp;class from the body when it changes. Our&nbsp;<code>useEffect<\/code>&nbsp;hook will look like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>useEffect(() =&gt; {\n  if (darkMode) {\n    document.body.classList.add(\"dark\");\n  } else {\n    document.body.classList.remove(\"dark\");\n  }\n}, &#91;darkMode]);\n<\/code><\/pre>\n\n\n\n<p>With this in place, our button starts to actually make some changes! When dark mode is active, we will see the following:<br><a href=\"https:\/\/res.cloudinary.com\/practicaldev\/image\/fetch\/s--w3NIubnp--\/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880\/https:\/\/storage.googleapis.com\/tobyhagan_post_images\/dark-mode-tutorial-active.webp\"><\/a><\/p>\n\n\n\n<h3><a href=\"https:\/\/dev.to\/lrth06\/dark-mode-using-react-279p#make-it-look-nice\"><\/a>Make it look nice<\/h3>\n\n\n\n<p>We need to update our button with a blank div to style into the slider button. First, remove the ternary statement from the label of the button, and replace it with a&nbsp;<code>div<\/code>&nbsp;element. Then, add a the class&nbsp;<code>.dark-mode-slider<\/code>&nbsp;to the div as shown below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;button\n  className=\"dark-mode-toggle\"\n  onClick={() =&gt; {\n    setDarkMode(!darkMode);\n  }}\n&gt;\n  &lt;div className=\"dark-mode-slider\" \/&gt;\n&lt;\/button&gt;\n<\/code><\/pre>\n\n\n\n<p>To achieve a nice slider look, we&#8217;ll update&nbsp;<code>src\/App.css<\/code>&nbsp;to add the&nbsp;<code>.dark-mode-toggle<\/code>&nbsp;and&nbsp;<code>.dark-mode-slider<\/code>&nbsp;classes from our button above. Add the following to&nbsp;<code>src\/App.css<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/* Button Styles *\/\n\n.dark-mode-toggle {\n  width: 80px;\n  height: 36px;\n  border-radius: 50px;\n  top: 0;\n  left: 0;\n}\n.dark-mode-toggle svg {\n  fill: #000;\n}\n.dark-mode-slider {\n  height: 30px;\n  width: 30px;\n  border-radius: 50%;\n  background-color: #2e3440;\n  display: flex;\n  position: relative;\n  transform: translateX(0px);\n  transition: all 0.2s ease;\n}\n\n.dark .dark-mode-slider {\n  transform: translateX(45px);\n}\n<\/code><\/pre>\n\n\n\n<p>Here you can see we have positioned the slider to the left for our default light mode, then when the&nbsp;<code>.dark<\/code>&nbsp;class is added to the body, we&#8217;ll move the slider to the right using CSS transitions. This will give the slider a nice sliding effect, giving your application a nice polished feel. This is just the beginning of what we can do with dark mode, as you can store values to local storage, then access them when the user returns to the site. We&#8217;ll be covering this in the next tutorial.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Dark mode is a common feature to see on modern websites, here&#8217;s how to make your own with React.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[30],"tags":[65],"_links":{"self":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2263"}],"collection":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2263"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2263\/revisions"}],"predecessor-version":[{"id":2264,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2263\/revisions\/2264"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2263"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2263"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2263"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}