Home >Web Front-end >CSS Tutorial >Dark Mode In React (vite)

Dark Mode In React (vite)

Patricia Arquette
Patricia ArquetteOriginal
2024-12-28 00:00:16504browse
**create a fresh folder
run the commands npm create vite@latest (in the folder directory)
also cd to the directory and run the command npm install**
step 1
`Code in App.jsx`
import React, { useState } from 'react';
import { FaSun, FaMoon } from 'react-icons/fa'; // Import Sun and Moon icons
import './App.css';

function App() {
  const [darkMode, setDarkMode] = useState(false);

  // Toggle dark mode
  const toggleTheme = () => {
    setDarkMode(!darkMode);
  };

  return (
    <div className={darkMode ? 'dark' : 'light'}>
      <div className="container">
        <h1>{darkMode ? 'Dark Mode' : 'Light Mode'}</h1>
        <button className="toggle-button" onClick={toggleTheme}>
          {darkMode ? <FaMoon className="icon" /> : <FaSun className="icon" />}
          {darkMode ? ' Dark Mode' : ' Light Mode'}
        </button>
      </div>
    </div>
  );
}

export default App;

Code in App.css
`body {
    margin: 0;
    font-family: Arial, sans-serif;
  }

  .container {
    text-align: center;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  /* Light Mode Styles */
  .light {
    background-color: #f9f9f9;
    color: #333;
  }

  /* Dark Mode Styles */
  .dark {
    background-color: #333;
    color: #f9f9f9;
  }

  /* Toggle Button Styles */
  .toggle-button {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 20px;
    border: none;
    border-radius: 30px;
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    background-color: #007bff;
    color: white;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
    transition: all 0.3s ease;
  }

  .toggle-button:hover {
    background-color: #0056b3;
    transform: scale(1.05);
  }

  .icon {
    font-size: 20px;
  }`

Final Output

Dark Mode In React (vite)

The above is the detailed content of Dark Mode In React (vite). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn