I've tried a variety of ways to fix this problem but can't seem to find a solution. Long story cut short, this is a hacky way of creating a dark mode toggle on my React app.
Essentially, I'd like the image src to change when the onClick event occurs. I've tried to add another function to the onClick but React throws an error about an infinite loop.
const App = () => {
const [lightMode, setLightMode ] = React.useState(false)
return (
<Router>
<div className={lightMode ? "light-mode" : "dark-mode"}>
<Container>
<Navbar.Brand className={lightMode ? "light-mode" : "dark-mode"} href="/">Built By Dan.</Navbar.Brand>
<img
className="mode-switch ml-auto"
onClick={() => setLightMode(prevMode => !prevMode)}
src="/media/bolt.png"
alt="lightning-bolt"
height="30px"
/>
</Container>
</Router>
I am unsure as to how to change the source. I've tried SCSS and a ternary operator but nothing seems to work.
Any help would be greatly appreciated here. All I would like to do is change the image when someone clicks the image and it toggles between colour schemes.
Thank you in advance!
I've tried a variety of ways to fix this problem but can't seem to find a solution. Long story cut short, this is a hacky way of creating a dark mode toggle on my React app.
Essentially, I'd like the image src to change when the onClick event occurs. I've tried to add another function to the onClick but React throws an error about an infinite loop.
const App = () => {
const [lightMode, setLightMode ] = React.useState(false)
return (
<Router>
<div className={lightMode ? "light-mode" : "dark-mode"}>
<Container>
<Navbar.Brand className={lightMode ? "light-mode" : "dark-mode"} href="/">Built By Dan.</Navbar.Brand>
<img
className="mode-switch ml-auto"
onClick={() => setLightMode(prevMode => !prevMode)}
src="/media/bolt.png"
alt="lightning-bolt"
height="30px"
/>
</Container>
</Router>
I am unsure as to how to change the source. I've tried SCSS and a ternary operator but nothing seems to work.
Any help would be greatly appreciated here. All I would like to do is change the image when someone clicks the image and it toggles between colour schemes.
Thank you in advance!
Share Improve this question asked Aug 2, 2020 at 23:30 BuiltByDanBuiltByDan 812 silver badges6 bronze badges1 Answer
Reset to default 5Use a ternary on the image src
to swap between both source urls.
<img
className="mode-switch ml-auto"
onClick={() => setLightMode(prevMode => !prevMode)}
src={lightMode ? "/path/to/img1" : "path/to/img2"}
alt="lightning-bolt"
height="30px"
/>