<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: ⚛️ Gayathri Perumal</title>
    <description>The latest articles on DEV Community by ⚛️ Gayathri Perumal (@gayathrithedev).</description>
    <link>https://dev.to/gayathrithedev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F497961%2F15ef1f12-9a14-4f74-bf6a-ec643ef0c55e.jpeg</url>
      <title>DEV Community: ⚛️ Gayathri Perumal</title>
      <link>https://dev.to/gayathrithedev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/gayathrithedev"/>
    <language>en</language>
    <item>
      <title>Light/Dark Mode toggle in React JS using Context API</title>
      <dc:creator>⚛️ Gayathri Perumal</dc:creator>
      <pubDate>Sun, 25 Oct 2020 12:40:37 +0000</pubDate>
      <link>https://dev.to/gayathrithedev/light-dark-mode-toggle-in-react-js-using-context-api-m7i</link>
      <guid>https://dev.to/gayathrithedev/light-dark-mode-toggle-in-react-js-using-context-api-m7i</guid>
      <description>&lt;p&gt;Hello &lt;strong&gt;Dev&lt;/strong&gt;,&lt;br&gt;
Now a days most of the websites have &lt;strong&gt;&lt;em&gt;dark and light mode&lt;/em&gt;&lt;/strong&gt;. In this post we will learn how to do that in your React application using the &lt;strong&gt;Context API&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Packages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.npmjs.com/package/react-switch" rel="noopener noreferrer"&gt;react-switch&lt;/a&gt; To implement the toggle switch (you can use button also)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.npmjs.com/package/react-icons" rel="noopener noreferrer"&gt;react-icons&lt;/a&gt; To use sunny and moon icon (you can use any icon packages)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;A quick &lt;a href="https://theme-context-api.vercel.app/" rel="noopener noreferrer"&gt;demo&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;To access the repo  &lt;a href="https://gitlab.com/pixie-dev/theme-using-context-api" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Concept to understand here:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Context API - Provider and Consumer. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The Provider act as a Global state. So the Root component of the project should be wrapped by the Provider&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Access the values stored in the provider using the Consumer at anywhere in your component&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The provider always holds the value(state) and methods that modify the state&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  First create a Provider.js
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;Provider.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, createContext } from "react";

export const ThemeContext = createContext();

const ThemeProvider = ({ children }) =&amp;gt; {
  const [mode, setTheme] = useState("light");
  return (
    &amp;lt;ThemeContext.Provider
      value={{
        mode,
        setTheme: () =&amp;gt; setTheme(mode === "dark" ? "light" : "dark")
      }}
    &amp;gt;
      {children}
    &amp;lt;/ThemeContext.Provider&amp;gt;
  );
};

export default ThemeProvider;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;createContext()&lt;/code&gt; creates a context object. Then defining a &lt;code&gt;state&lt;/code&gt; named &lt;code&gt;mode&lt;/code&gt; by default it as &lt;strong&gt;light&lt;/strong&gt; value. And the &lt;code&gt;setTheme&lt;/code&gt; is an action that modifies the &lt;code&gt;mode&lt;/code&gt; value.&lt;br&gt;
Then creating the Provider component by default it accepts &lt;code&gt;value&lt;/code&gt; as a prop. Notice that: The &lt;code&gt;value&lt;/code&gt; prop has &lt;code&gt;mode&lt;/code&gt; and &lt;code&gt;setTheme&lt;/code&gt; properties.&lt;/p&gt;

&lt;p&gt;The provider component returns a &lt;code&gt;children&lt;/code&gt;. i.e where ever we wrap this provider that component will be considered as &lt;code&gt;root&lt;/code&gt; of this context provider.&lt;/p&gt;

&lt;p&gt;From the above code we initialized &lt;code&gt;ThemeContext&lt;/code&gt; and Created our &lt;code&gt;ThemeProvider&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  Create theme.js
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;theme.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const theme = {
  light: {
    color: "#03dac5",
    backgroundColor: "#ffffff",
    highlight: "#fdb813"
  },
  dark: {
    color: "#bb86fc",
    backgroundColor: "#121212",
    highlight: "#ffffff"
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Theme is just an &lt;code&gt;object&lt;/code&gt; containing values corresponding to the modes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Wrap the ThemeProvider in the root component
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;index.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

import ThemeProvider from "./Provider";

const rootElement = document.getElementById("root");
ReactDOM.render(
  &amp;lt;ThemeProvider&amp;gt;
    &amp;lt;React.StrictMode&amp;gt;
      &amp;lt;App /&amp;gt;
    &amp;lt;/React.StrictMode&amp;gt;
  &amp;lt;/ThemeProvider&amp;gt;,
  rootElement
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the root component is &lt;code&gt;index.js&lt;/code&gt;. Now the Provider is available globally, we can use the consumer in any where inside our components to access the &lt;code&gt;value&lt;/code&gt; from the provider.&lt;/p&gt;

&lt;h3&gt;
  
  
  Access the values from the provider
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;App.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useContext } from "react";

import { theme } from "./theme";

import { ThemeContext } from "./Provider";

const getStyles = (mode) =&amp;gt; ({
  header: {
    fontSize: 34,
    fontWeight: "400"
  },
  app: {
    height: "100%",
    width: "100%",
    padding: 16,
    backgroundColor: theme[mode].backgroundColor
  },
  text: {
    fontWeight: "200",
    color: theme[mode].color
  },
  theme: {
    color: theme[mode].highlight
  }
});

export default function App() {
  const { mode } = useContext(ThemeContext);
  const styles = getStyles(mode);
  return (
    &amp;lt;div style={styles.app}&amp;gt;
      &amp;lt;h1 style={(styles.header, styles.text)}&amp;gt;
        Have a nice day... DEV!
      &amp;lt;/h1&amp;gt;
      &amp;lt;h2 style={styles.text}&amp;gt;
        Current theme is &amp;lt;span style={styles.theme}&amp;gt;{mode}&amp;lt;/span&amp;gt; mode
      &amp;lt;/h2&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the above code, we are trying to access the &lt;code&gt;mode&lt;/code&gt; value. So at first we need to say what context object we are trying to access(ThemeContext).&lt;/p&gt;

&lt;p&gt;You notice that, &lt;code&gt;mode&lt;/code&gt; value is passed to &lt;code&gt;styles&lt;/code&gt;, here based on the &lt;code&gt;mode&lt;/code&gt; we are changing the text color and background color.&lt;/p&gt;

&lt;h3&gt;
  
  
  Time to create a toggle switch
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;ThemeSwitch.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useContext } from "react";

import Switch from "react-switch";
import { IoMdSunny, IoMdMoon } from "react-icons/all";

import { ThemeContext } from "./Provider";

const getStyles = (mode) =&amp;gt; ({
  switch: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    height: "100%",
    fontSize: 35,
    paddingLeft: mode === "dark" ? 30 : 10
  }
});

const ThemeSwitch = () =&amp;gt; {
  const { setTheme, mode } = useContext(ThemeContext);
  const styles = getStyles(mode);
  return (
    &amp;lt;Switch
      checked={mode === "light" ? true : false}
      height={50}
      width={120}
      offColor="#1d1f2f"
      onColor="#FDB813"
      checkedIcon={
        &amp;lt;IoMdSunny style={styles.switch} color="white" className="light" /&amp;gt;
      }
      uncheckedIcon={
        &amp;lt;IoMdMoon style={styles.switch} color="white" className="dark" /&amp;gt;
      }
      onChange={setTheme}
    /&amp;gt;
  );
};

export default ThemeSwitch;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we are handling the &lt;code&gt;setTheme&lt;/code&gt; method when the toggle switch is clicked. And based on the &lt;code&gt;mode&lt;/code&gt; we are updating the icons and colors.&lt;/p&gt;

&lt;h3&gt;
  
  
  Finally add the toggle switch inside the component
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;App.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useContext } from "react";

import { theme } from "./theme";

import { ThemeContext } from "./Provider";
import ThemeSwitch from "./ThemeSwitch";

const getStyles = (mode) =&amp;gt; ({
  header: {
    fontSize: 34,
    fontWeight: "400"
  },
  app: {
    height: "100%",
    width: "100%",
    padding: 16,
    backgroundColor: theme[mode].backgroundColor
  },
  text: {
    fontWeight: "200",
    color: theme[mode].color
  },
  theme: {
    color: theme[mode].highlight
  }
});

export default function App() {
  const { mode } = useContext(ThemeContext);
  const styles = getStyles(mode);
  return (
    &amp;lt;div style={styles.app}&amp;gt;
      &amp;lt;h1 style={(styles.header, styles.text)}&amp;gt;Have a nice day... DEV!&amp;lt;/h1&amp;gt;
      &amp;lt;h2 style={styles.text}&amp;gt;
        Current theme is &amp;lt;span style={styles.theme}&amp;gt;{mode}&amp;lt;/span&amp;gt; mode
      &amp;lt;/h2&amp;gt;
      &amp;lt;ThemeSwitch /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Added  &lt;code&gt;&amp;lt;ThemeSwitch /&amp;gt;&lt;/code&gt; in &lt;code&gt;App.js&lt;/code&gt;. Now play with toggle switch to notice the changes.&lt;/p&gt;

&lt;p&gt;That's all, you can add this &lt;code&gt;ThemeSwitch&lt;/code&gt; component any where inside your project to change the theme.&lt;/p&gt;

&lt;p&gt;🎉 Tada... We are done... &lt;/p&gt;

&lt;p&gt;Thanks 😃 for the read...&lt;/p&gt;

&lt;p&gt;Drop a ♥️ if this content is helpful...&lt;/p&gt;

&lt;p&gt;Suggestions and doubts are always welcome in the comment section... &lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>codenewbie</category>
    </item>
  </channel>
</rss>
