I have a darkMode toggle as a separate component (grandchild) which is embedded in a Navbar component (child). That Navbar component is called in the App component (parent).
Essentially, my goal is that when I toggle the darkMode/lightMode button in the DarkMode component, it sends this 'event' through the Navbar and up to the App.js where the CSS change will be called and is dependent on a conditional operator.
I've tried to pass some props with what basic knowledge I have, but I can't seem to work out how to actually pass the state/event.
I'm not sure if what I am trying to do is even achievable and/or is too complex, so would really appreciate suggestions. I know I can place all of this code in the App.js, but I wanted to separate my components.
App.js (parent)
const App = () => {
const [darkMode, setDarkMode] = useState(true);
return (
<div className={darkMode ? "darkmode" : "lightmode"}>
<Navbar darkMode={darkMode}/>
<Hero />
</div>
);
}
Navbar.js (child)
const Navbar = ({darkMode}) => {
return (
<div className="row">
<div className="col">
<h3>This is the Navbar component</h3>
</div>
<div className="col">
{/* This is the DarkMode component button */}
<DarkMode darkMode={darkMode} />
</div>
</div>
)
}
DarkMode.js (grandchild)
const DarkMode = ({darkMode}) => {
const [isDarkMode, setDarkMode] = useState(false);
const [imageSrc, setImageSrc] = useState(SunIcon);
const switchModes = () => {
setDarkMode(prevMode => !prevMode);
isDarkMode ? setImageSrc(SunIcon) : setImageSrc(MoonIcon);
};
return (
<>
<button>
<img
className=""
onClick={switchModes}
src={imageSrc}
alt="lightning-bolt"
height="30px"
/>
</button>
</>
)
}