How to Build a React App with Authentication and Theme Toggling using React Router and Context API

Have you ever wondered how to implement a theme toggle in your React app, or how to handle user authentication? In this blog, we'll explore how to do both, and more! We'll walk through the code step-by-step and provide helpful explanations along the way. Whether you're a beginner or an experienced React developer, you're sure to learn something new. So, let's dive in and start building a dynamic React app with a theme toggle and user authentication!

Why did the programmer quit his job?

Because he didn't get a good response from the chatbot he built! ;)

Learn how to use React Context API, Routes, and State Management by building a Login/Logout and Theme Toggling feature in a React App.


ThemeContext and AuthContext and :

We use ThemeContext in React to provide a consistent visual style throughout an application. By defining a theme object that contains styles for various UI components, we can easily apply those styles to any component that needs them.

Using ThemeContext also makes it easy to update the visual style of an application, since we only need to change the theme object in one place to update all components that use it.

Another benefit of using ThemeContext is that it allows us to customize the visual style of our application based on user preferences or other factors, such as a user's operating system or browser settings. This can improve the user experience and make our application more accessible to a wider range of users.

In React, Auth Context is a way to manage and share authentication-related data and functions throughout your application. It allows you to pass data down to any component in the component tree without having to pass the data explicitly through props at every level.

Auth Context is implemented using the React Context API, which provides a way to share data across multiple components without having to pass the data down through props. With Auth Context, you can store information about whether a user is authenticated or not, as well as any other relevant information, such as their username or role.

To use Auth Context, you create a Context object using the createContext() method from the React library. You can then provide a value to this Context object at a high-level component in your app, such as the top-level App component. This value can be an object containing the authentication state and any relevant functions.

You can then consume the Auth Context in any child component by using the useContext() hook, which allows you to access the value provided by the Context object.

Let's Buils:

here's an example of how you can create a React app with a button to change the theme and two buttons to toggle the user login status using Context API:

File-Structure:

  1. App.js - This is the main component that renders all other components. It sets the app's theme, handles the login/logout functionality, and contains the app's routes.

  2. AuthContext.js - This file contains a context for handling authentication throughout the app. It provides a boolean value to determine if the user is authenticated and a function to toggle the authentication state.

  3. Dashboard.js - This component displays the dashboard page of the app. It displays different content depending on whether the user is authenticated or not. If the user is authenticated, it displays a logout button, otherwise, it displays a message asking the user to log in.

  4. Home.js - This component displays the home page of the app. It displays different content depending on whether the user is authenticated or not. If the user is authenticated, it displays a message saying that the user is logged in, otherwise, it displays a login button.

  5. ThemeContext.js - This file contains a context for handling the theme of the app. It provides a string value to determine the current theme and a function to toggle the theme state.

All of these files work together to create a simple React app that demonstrates how to use context, routes, and state in a practical way.

  1. First, create a new React app by running the following command in your terminal:

  2.     npx create-react-app my-app
        cd my-app
    
  3. Next, install the required dependencies:

npm install react-router-dom react-icons
  1. AuthContext.js:

    This file contains the authentication context, which is used to track the authenticated state of the user. It exports the AuthProvider component, which provides the authentication state and a function to toggle it to its child components.

    Create a new file called AuthContext.js in the Context folder in src folder and add the following code:

  2.     import React, { createContext, useState } from "react";
    
        export const AuthContext = createContext();
    
        export const AuthProvider = ({ children }) => {
          // State for user authentication
          const [isAuthenticated, setIsAuthenticated] = useState(false);
    
          // Function to toggle authentication
          const toggleAuth = () => {
            setIsAuthenticated((prevState) => !prevState);
          };
    
          return (
            // AuthContext provider with the current authentication state and toggleAuth function
            <AuthContext.Provider value={{ isAuthenticated, toggleAuth }}>
              {children}
            </AuthContext.Provider>
          );
        };
    
  3. themeContext.js:

    This file contains the theme context, which is used to track the current theme of the application. It exports the ThemeContext component, which provides the theme to its child components.

import { createContext } from "react";

// Create a context with a default value of "light"
export const ThemeContext = createContext("light");

App.js

This is the main component that renders the routes for the entire application. It also contains the ThemeContext Provider that holds the theme state and passes it to all child components. There are two routes defined in this file for the Home and Dashboard components.

import React, { useState } from "react";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import { ThemeContext } from "./../src/Contexts/themeContext";
import Home from "./Home";
import Dashboard from "./Dashboard";

function App() {
  // State for theme (light or dark)
  const [theme, setTheme] = useState("light");

  // State for user authentication
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  // Function to toggle the theme between light and dark
  const toggleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  // Function to handle login
  const handleLogin = () => {
    setIsLoggedIn(true);
  };

  // Function to handle logout
  const handleLogout = () => {
    setIsLoggedIn(false);
  };

  return (
    // ThemeContext provider with the current theme value
    <ThemeContext.Provider value={theme}>
      <Router>
        {/* Navigation */}
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/dashboard">Dashboard</Link>
            </li>
          </ul>
        </nav>
        {/* Button to toggle the theme */}
        <button onClick={toggleTheme}>Toggle Theme</button>
        {/* Current theme value */}
        <p>{theme} </p>
        {/* Main content */}
        <div
          style={{
            // Set background color to white for light theme, black for dark theme
            backgroundColor: theme === "light" ? "white" : "black",
            // Set text color to black for light theme, white for dark theme
            color: theme === "dark" ? "white" : "black"
          }}
        >
          <Routes>
            {/* Route for Home page */}
            <Route
              path="/"
              element={
                <Home isLoggedIn={isLoggedIn} handleLogin={handleLogin} />
              }
            />
            {/* Route for Dashboard page */}
            <Route
              path="/dashboard"
              element={
                <Dashboard
                  isLoggedIn={isLoggedIn}
                  handleLogout={handleLogout}
                />
              }
            />
          </Routes>
        </div>
      </Router>
    </ThemeContext.Provider>
  );
}

export default App;

Dashboard.js

This component displays a simple dashboard page that is only accessible when the user is authenticated. It takes two props, isLoggedIn and handleLogout, which are used to control the authentication state and handle the logout action.

import React from "react";

function Dashboard({ isLoggedIn, handleLogout }) {
  return (
    <div>
      <h2>Dashboard Page</h2>
      {isLoggedIn ? (
        // Show "You are logged in" and "Log Out" button if user is logged in
        <>
          <p>You are logged in.</p>
          <button onClick={handleLogout}>Log Out</button>
        </>
      ) : (
        // Show "You are not logged in" if user is not logged in
        <p>You are not logged in.</p>
      )}
    </div>
  );
}

export default Dashboard;

Home.js:

This component displays a simple home page that is accessible to all users, but prompts the user to log in if they are not authenticated. It takes two props, isLoggedIn and handleLogin, which are used to control the authentication state and handle the login action.

import React from "react";

function Home({ isLoggedIn, handleLogin }) {
  return (
    <div>
      <h2>Home Page</h2>
      {/* Display different content based on login status */}
      {isLoggedIn ? (
        <p>You are logged in.</p>
      ) : (
        <button onClick={handleLogin}>Log In</button>
      )}
    </div>
  );
}

export default Home;

In addition, we have provided a CodeSandbox link that contains all the code used in this tutorial. You can use this to experiment with the code and make changes to see how they affect the app's behavior. The CodeSandbox also includes a live preview of the app, so you can see how the changes affect the UI in real-time. We hope that this resource will be helpful in your learning journey and encourage you to continue exploring the world of React and web development ->

Why did the developer quit his job?

Because he didn't get arrays!

In conclusion, understanding React Context API and React Router is essential for any React developer. In this blog post, we learned how to use the Context API to share data between components without having to pass props down the component tree. We also learned how to use React Router to navigate between different pages in a React application. We implemented a simple login/logout functionality along with a theme toggle feature to demonstrate how these concepts can be used in real-world scenarios.

We hope that this blog post has helped you gain a better understanding of these two important concepts in React. Remember, this is just the tip of the iceberg when it comes to React, and there's a lot more to learn. With practice, you'll be able to build amazing web applications with ease.

here are some helpful resources for learning more about React:

  1. React documentation: reactjs.org/docs/getting-started.html

  2. React Router documentation: reactrouter.com/web/guides/quick-start

  3. Context API documentation: reactjs.org/docs/context.html

  4. Context API:

    https://anujpancholi.hashnode.dev/react-context-api-the-ultimate-guide-for-efficient-data-sharing-in-react-applications

  5. React tutorial on Codecademy: codecademy.com/learn/react-101

  6. React tutorial on freeCodeCamp: freecodecamp.org/learn/front-end-libraries/..

  7. React tutorial on Udemy: udemy.com/topic/react

  8. React tutorial on Pluralsight: pluralsight.com/paths/react

  9. React tutorial on YouTube by Traversy Media: youtube.com/watch?v=sBws8MSXN7A

  10. React tutorial on YouTube by Net Ninja: youtube.com/watch?v=O6P86uwfdR0&list=PL..

I hope you find these resources helpful!


Note: Please keep in mind that this is not a static blog post. As technology constantly evolves, there may be updates or changes to the code and methods discussed in this article. We will do our best to keep this post up-to-date.


Thank you for reading, and we wish you all the best on your React journey!