search

Home  >  Q&A  >  body text

Conditionally change className to css module (React)

<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粉799885311P粉799885311454 days ago500

reply all(1)I'll reply

  • P粉124890778

    P粉1248907782023-08-18 10:25:38

    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

    reply
    0
  • Cancelreply