How to use Bootstrap’s built-in dark mode In ReactJS

  • In this approach, we are using Bootstrap’s built-in dark mode by toggling a state (isDarkMode) to switch between light and dark themes.
  • The container’s background and text color classes (bg-dark, text-light for dark mode, and bg-light for light mode) are dynamically applied based on the state.
  • The toggleDarkMode function switches the theme when the toggle button is clicked.

Example: Implementation of the above approach.

JavaScript
// Filename - App.js

import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Container, Button } from 'react-bootstrap';

function App() {
  const [isDarkMode, setIsDarkMode] = useState(false);

  const toggleDarkMode = () => {
    setIsDarkMode((prevMode) => !prevMode);
  };

  return (
    <>
      <h1 className="text-center mb-5">
          Using Bootstrap's built-in dark mode
       </h1>
      <Container
        className={`d-flex flex-column justify-content-center 
        align-items-center ${isDarkMode ? 
        'bg-dark text-light' : 'bg-light'}`}
        style={{ minHeight: '70vh' }}
      >
        <h1>{isDarkMode ? 'Dark Theme' : 'Light Theme'}</h1>
        <Button variant="primary" onClick={toggleDarkMode}>
          Toggle Theme
        </Button>
      </Container>
    </>
  );
}

export default App;

Output:

How to Create Dark/Light Theme in Bootstrap with React?

Creating dark/light themes and integrating them into a React application enhances user experience by providing visual customization options, improving readability, and allowing users to switch between themes based on their preferences. In this article, we will learn to create dark/light theme in Bootstrap 5 with React.

Table of Content

  • Using Bootstrap’s built-in dark mode
  • Using Bootstrap’s Theme Classes

Similar Reads

Steps to Create the React Application

Step 1: Create React Project...

Using Bootstrap’s built-in dark mode

In this approach, we are using Bootstrap’s built-in dark mode by toggling a state (isDarkMode) to switch between light and dark themes. The container’s background and text color classes (bg-dark, text-light for dark mode, and bg-light for light mode) are dynamically applied based on the state. The toggleDarkMode function switches the theme when the toggle button is clicked....

Using Bootstrap’s Theme Classes

In this approach, we are using Bootstrap’s theme classes to toggle between dark and light themes in React. By dynamically adding the “theme-dark” or “theme-light” class to the main container, we control the overall theme appearance. Additionally, we utilize the data-bs-theme attribute on the HTML element to apply Bootstrap’s built-in dark mode feature for a consistent styling experience....