Home > Software design >  React changes class names after compilation. querySelector became useless
React changes class names after compilation. querySelector became useless

Time:08-08

I'm new to react, so maybe there is a way around. I know React uses virtual DOM and etc, I'm even getting used to it, but this time I know no way around.

I have a menu that expandes, so I created the code:

function OnClickExpander(){
      var expander = document.querySelector(".expanderInactive");
      expander.className="expanderActive";
}

And I put the code here:

<div className={Styles.expanderIcon} onClick={OnClickExpander}><FaAlignJustify/></div>

It should work, but It doesn't because react changes the classnames after it compiles. So I got the new class names and put it there. Worked fine, but I wonder if react is gonna change all of sudden again, maybe after updating react, because I feel like it's a quick-fix and not a final solution. How would you do this code?

import Styles from './Navbar.module.css';
import {Link} from 'react-router-dom';
import { FaAlignJustify } from "react-icons/fa";

function OnClickExpander(){
      var expander = document.querySelector(".Navbar_expanderInativo__MnF1u");
      expander.className="Navbar_expanderAtivo__B-4WW";
}


function Navbar(){
   return(
    <div>
      <div className={Styles.expanderInativo}>a</div>
      <div>
         <ul className={Styles.menuSuperior}>
               <li>Todos</li>
               <li>Esportes</li>
               <li>Novelas</li>
               <li>Minha Cidade</li>
         </ul>
      </div>
      <div className={Styles.MenuContainer}>
         <div className={Styles.expanderIcon} onClick={OnClickExpander}><FaAlignJustify/></div>
         <ul className={Styles.menu}>
            <li><Link to="/">Inicio</Link></li>
            <li><Link to="/contato">Contato</Link></li>
            <li><Link to="/sobre">Sobre</Link></li>
         </ul>
      </div>

    </div>
   );
}

export default Navbar;

CodePudding user response:

The random class names you're seeing come from css modules. They can be used with react, but they aren't a part of react. In any event, you should not be doing direct dom manipulation in react. Instead, use the standard react technique: state. When you render, check the state and use that to pick the class name. When you want to change the class name, change the state.

function Navbar() {
  const [expanded, setExpanded] = useState(false)

  // ...
  <div className={expanded ? Styles.expanderActive : Styles.expanderActive}>a</div>
  // ...
  <div className={Styles.expanderIcon} onClick={() => {
    setExpanded(!expanded)
  }}><FaAlignJustify/></div>
}
  • Related