30
loading...
This website collects cookies to deliver better user experience
import React,{useState} from 'react'
function App() {
const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = () => setDarkMode(!darkMode);
return (
<div>
<div className={darkMode ? 'bg-dark text-light text-center p-4' : 'bg-light text-dark text-center p-4'}>
<h1 className='display-1'>Some text inside this box </h1>
</div>
<div className='text-center my-5'>
<button className='btn btn-primary' onClick={toggleDarkMode}>{darkMode ? 'Light mode' : 'Dark mode'}</button>
</div>
</div>
)
}
export default App
Then we have a button which has an onClick event handler which calls the toggleDarkMode arrow function when clicked and change the state of "darkMode" to true if it is false and to false if it is true , this button will enable and disable dark mode theme.
We have also used ternary opertor in button text in which the text will be "light mode" if the state of "darkMode" is true and text will be "dark mode" if the state of "darkMode" is false.
import React,{useState} from 'react'
function App() {
const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = () => setDarkMode(!darkMode);
const styleDiv = {
backgroundColor:darkMode ? 'black' : 'white',
color: darkMode ? 'white' : 'black',
textAlign:'center',
padding:'2rem'
}
return (
<div>
<div style={styleDiv}>
<h1 className='display-1'>Some text inside this box </h1>
</div>
<div className='text-center my-5'>
<button className='btn btn-primary' onClick={toggleDarkMode}>{darkMode ? 'Light mode' : 'Dark mode'}</button>
</div>
</div>
)
}
export default App