DEV Community

打coding的奥特曼
打coding的奥特曼

Posted on

Implement Dark Mode in Tailwind React Application

1.active dark mode in tailwind.config.js

module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  darkMode: 'class',
  theme: {
    extend: {
    },
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

2. set dark mode in App.js , and pass {dark,setDark} to ,in which we set the toggle method in

function App() {
  const [dark,setDark]=useState(false);
  return (
    <div className={dark?"dark":''}>
      <Nav props={{dark,setDark}}/>
      <Routes>
        <Route path="/" element={<Home />}/>
      </Routes>
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

3.set the toggle in the component

Nav.jsx,sun and moon are the icon you choose for it

function Nav({props}) {
  const {dark,setDark} = props
  const handleClick = ()=>{
    setDark(!dark)
  }
  return (
  <>
   <img src={dark?sun:moon} alt="toggle" className="w-5 h-5 
    absolute cursor-pointer" onClick={handleClick}/>
  </>
export default Nav;
Enter fullscreen mode Exit fullscreen mode

4. add dark mode to the components ,such as About.js

function About(props) {
  console.log(skills)
  return (
    <div id='about' className=' dark:bg-gray-700 dark:text-white'>

    </div>
  );
}

export default About;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)