Conditionally change className to css module (React)
P粉799885311
P粉799885311 2023-08-17 18:10:17
0
1
497
<p>I'm trying to play an animation when the user hovers over my website's navigation bar. I'm trying to achieve this by changing a css module based on whether the mouse is hovering over the navigation bar. I'm trying to figure out why this code isn't working. Any help is greatly appreciated! </p> <p>Navbar.jsx:</p> <pre class="brush:php;toolbar:false;">import React, { useState } from "react"; import { Link } from "react-router-dom"; import styles from "../styles/Navbar.module.css"; const Navbar = () => { const [className, setClassName] = useState("line-after"); return ( <div className="navbar" onMouseEnter={() => setClassName("line::before")} onMouseLeave={() => setClassName("line-after")} > <nav> <Link to="/about" className="home-page"> Bob <br /> Jones </Link> <ul> <li> <Link to="/about" className="about-page"> About </Link> </li> <li> <Link to="/resume" className="resume-page"> Resume </Link> </li> <li> <Link to="/contact" className="contact-page"> Contact </Link> </li> </ul> </nav> <div className={styles.className}></div> </div> ); }; export default Navbar;</pre> <p>Css module: </p> <pre class="brush:php;toolbar:false;">.line::before { content: ""; position: absolute; top: 0; left: 0; width: 55px; height: 1px; background: black; animation-name: animate; animation-duration: 1s; } .line-after { margin: 40px 40px 40px 40px; width: 55px; height: 1px; background: white; position: relative; } @keyframes animate { 0% { left: 0; } 100% { left: 100%; } }</pre> <p>I am changing the state of the className when the mouse leaves and enters the navigation bar. However, it says that my state variable className is never used, so I think that's the problem. Not sure how to fix it. </p>
P粉799885311
P粉799885311

reply all(1)
P粉124890778

You can achieve this without using React logic at all, you can simply use CSS animations (like you are currently doing) and CSS pseudo-classes ( :hover in this case) instead of dynamic Change the element's class manually.

https://developer.mozilla.org/en-US/docs/Web/CSS/:hover

Please check if this works for you: How to play animation on hover and pause on hover inactive

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template