'React ref vs state to manipulate className
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.
Solution 1:[1]
In react documentation, it's said not to overuse react refs so I think using state would be the better.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | exo__ |
