This was pretty simple in Vanilla JS but I'm struggling to implement this in React.
I have Navbar with some links. Upon hovering over each link, I'd like the background color of the entire Navbar (classname: nav-section) to change accordingly. And by default I want to have a black color for the page. Anytime the cursor is not on any of the links, the navbar should be back to black again.
Say, my simplified Navbar.js is like this:
const Navbar = () => {
return (
<nav className='nav-section'>
<div className="nav-list">
<a className="list-item one">
<div className="navlink-text">Red</div>
</a>
<a className="list-item two">
<div className="navlink-text">Blue</div>
</a>
<a className="list-item three">
<div className="navlink-text">Aqua</div>
</a>
<a className="list-item four">
<div className="navlink-text">Cyan</div>
</a>
</div>
</nav>
);
};
export default Navbar;
I have an external css file styling the navbar and other elements that I have in it. What is the most efficient way to achieve what I want, with React? I tried to use emotion/css but I couldn't make it work. Any guidance is well appreciated.
Leaving this for anyone who comes across this post,
I solved it using Emotion.
/** @jsxImportSource @emotion/react */
import { useState } from "react";
import "./navbar.css";
import { css } from "@emotion/react";
const Navbar = () => {
const [background, setBackground] = useState("#410099");
const setStyle = (background) => {
setBackground(background);
};
return (
<nav css={css`
position: sticky;
left: 0;
top: 0;
right: 0;
bottom: auto;
z-index: 998;
background-color: ${background};
display: flex;
flex-direction: column;
padding: 0px 60px;
`}
>
<div className="nav-list">
<a
className="list-item one"
onMouseEnter={() => setStyle("#424246")}
onMouseLeave={() => setStyle("#410099")}
>
<div className="navlink-text">Color</div>
</a>
<a className="list-item two"
onMouseEnter={() => setStyle("#424246")}
onMouseLeave={() => setStyle("#410099")}>
<div className="navlink-text">Color</div>
</a>
<a className="list-item three"
onMouseEnter={() => setStyle("#424246")}
onMouseLeave={() => setStyle("#410099")}>
<div className="navlink-text">Color</div>
</a>
<a className="list-item four"
onMouseEnter={() => setStyle("#424246")}
onMouseLeave={() => setStyle("#410099")}>
<div className="navlink-text">Color</div>
</a>
</div>
</nav>
);
};
export default Navbar;
Customize this as needed. :)