Switch Between Light and Dark

ReactReactBeginner
Practice Now

Introduction

In this project, you will learn how to create a React application that allows users to switch between light and dark mode. The project will demonstrate the usage of the React Context API and the useContext hook to manage the global theme state.

👀 Preview

project preview

ðŸŽŊ Tasks

In this project, you will learn:

  • How to create a ThemeContext using React's Context API
  • How to use the ThemeContext in the App component to change the overall app style based on the theme
  • How to use the ThemeContext in the Card component to change the card styles based on the theme
  • How to wrap the App component with the ThemeProvider to make the theme context available throughout the application

🏆 Achievements

After completing this project, you will be able to:

  • Understand how to use the React Context API to manage global state
  • Apply the useContext hook to access the context values
  • Implement different styles based on the current theme
  • Toggle the theme and update the global state

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/AdvancedConceptsGroup -.-> react/context_api("`Context API`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/context_state("`Using Context for State`") subgraph Lab Skills react/jsx -.-> lab-300148{{"`Switch Between Light and Dark`"}} react/context_api -.-> lab-300148{{"`Switch Between Light and Dark`"}} react/hooks -.-> lab-300148{{"`Switch Between Light and Dark`"}} react/context_state -.-> lab-300148{{"`Switch Between Light and Dark`"}} end

Set Up the Project

In this step, you will learn how to set up the project and install the necessary dependencies.

Open your code editor and navigate to the project directory.

├── components
│ └── Card.js
├── contexts
│ └── ThemeContext.js
├── App.css
├── App.js
├── index.css
├── index.js
├── reportWebVitals.js
└── setupTests.js

File descriptions:

  • The components directory contains all component files.
  • The contexts directory contains the ThemeContext.js file that needs to be completed.

Since this is a React project, we need to install the dependencies by running the following command:

npm install

After installing the dependencies, follow these steps to access the project:

  1. Start a local server by running the following command in the terminal:
npm start
  1. Open the web server on the right side of the coding environment. You will see the static effect as shown below. Currently, clicking the "Dark Mode" button does not cause any changes.
Incomplete

Create the ThemeContext

In this step, you will learn how to create the ThemeContext using React's Context API. Follow the steps below to complete this step:

  1. Open the ThemeContext.js file located in the src/contexts directory.

  2. Create the ThemeContext using React.createContext():

    export const ThemeContext = React.createContext();
  3. Create the ThemeProvider component that will wrap the App component and provide the theme context:

    export const ThemeProvider = (props) => {
      const [theme, setTheme] = React.useState("light");
      return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
          {props.children}
        </ThemeContext.Provider>
      );
    };

    The ThemeProvider component initializes the theme state to "light" and provides the theme and setTheme values to the context.

Use the ThemeContext in the App component

In this step, you will learn how to use the ThemeContext in the App component to change the overall app style based on the theme.

  1. Open the src/App.js file.

  2. Use the useContext hook to access the theme value from the ThemeContext:

    const { theme } = useContext(ThemeContext);
  3. Update the App component's JSX to apply different styles based on the theme value:

    return (
      <div className={theme === "light" ? "app app-light" : "app app-dark"}>
        <Card></Card>
      </div>
    );

    The app-light and app-dark classes will be applied to the main div element based on the theme value.

Use the ThemeContext in the Card component

In this step, you will learn how to use the ThemeContext in the Card component to change the card styles based on the theme.

  1. Open the src/components/Card.js file.

  2. Use the useContext hook to access the theme and setTheme values from the ThemeContext:

    export const Card = () => {
      const { theme, setTheme } = useContext(ThemeContext);
      // ...
    };
  3. Implement the handleThemeToggle function to toggle the theme:

    const handleThemeToggle = (e) => {
      setTheme(theme === "light" ? "dark" : "light");
    };

    This function will update the theme value in the ThemeContext when the button is clicked.

Wrap the App component with the ThemeProvider

In this final step, you will learn how to wrap the App component with the ThemeProvider to make the theme context available throughout the application.

  1. Open the src/index.js file.

  2. Import the ThemeProvider from the ThemeContext.js file:

    import { ThemeProvider } from "./contexts/ThemeContext";
  3. Wrap the App component with the ThemeProvider in the ReactDOM.render function:

    root.render(
      <React.StrictMode>
        <ThemeProvider>
          <App />
        </ThemeProvider>
      </React.StrictMode>
    );

Now, the App component and its child components can access the theme and setTheme values from the ThemeContext using the useContext hook.

After completing the challenge, the effect should be as follows:

Complete

Congratulations! You have completed the project. You should now be able to switch between light and dark mode by clicking the button in the card component.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like