1

So I found two ways to dynamically change the className of react component. But which one is the best and most efficient?

Using ref:

class Header extends React.Component{
    dropdownRef = React.createRef()
    
    handleDropdown = () =>{
      this.dropDownRef.current.classList.toggle('open')
    };
    
    render(){
       return(
          <header>
              <div ref={this.dropdownRef} className="dropdown">
                Hello
              </div>
              <button onClick={this.handleDropdown}>Click Me!</button>
           </header>)
    }

}

Using state:

class Header extends React.Component{
    state = {isOpen : false }

    handleDropdown = () =>{
       this.setState(prev=>({
           isOpen: !prevState.isOpen
       }))
    };

    render(){
       return(
          <header>
             <div className={`dropdown ${this.state.isOpen ? "open" : ""}`}>
               Hello
             </div>
             <button onClick={this.handleDropdown}>Click Me!</button>
          </header>)
    }
}

So which one is the best way to change the class or do similar things.

  • Changing a ref won't re-render the component. Just keep that in mind and decide for yourself what is more suitable for your needs. – MauriceNino May 11 '22 at 07:57
  • Does this answer your question? [React: useState or useRef?](https://stackoverflow.com/questions/56455887/react-usestate-or-useref) – MauriceNino May 11 '22 at 07:58

1 Answers1

0

In react documentation, it's said not to overuse react refs so I think using state would be the better.

exo__
  • 11
  • 3
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – tjheslin1 May 12 '22 at 08:46