Search code examples
javascriptreactjsflagsclassname

toggle className using flag


const [flag, setFlag] = useState(false)

let visibleActive, visibleTransition

const handleSelect = () => {
    setFlag(!flag)
    visibleActive = flag ? 'visible active' : ''
    visibleTransition = flag ? 'visible transition' : ''
    console.log(flag)
    console.log(visibleActive)
    console.log(visibleTransition)
}

return (
    <>
        <div className="ui form">
            <div className="field">
                <label className="label">Select a color</label>
                <div className={`ui selection dropdown ${visibleActive}`} onClick={handleSelect}>
                    <i className="dropdown icon"></i>
                    <div className="text">Select Color</div>
                    <div className={`menu ${visibleTransition}`}>
                    </div>
                </div>
            </div>
            
        </div>
    </>
)

classes don't toggle when I click on the dropdown. I see the results in the console but the same is not applying on the JSX. The variables 'visibleTransition' and 'visibleActive' have the correct values but still these values are not being applied.


Solution

  • React setState calls are batched and enqueued and state updates may be async. You cannot access the flag state immediately after setting it.

    The visibleActive, visibleTransition variables will loose their values after re-render. You can use useRef to maintain a value between re-renders.

    import {useRef} from 'react'
    
    const visibleActive = useRef("")
    const visibleTransition = useRef("")
    

    You can assign a value to ref like visibleActive.current = flag ? "visible active" : "";

    and Use useEffect to get the correct flag state value

    useEffect(() => {
      visibleActive.current = flag ? "visible active" : "";
      visibleTransition.current = flag ? "visible transition" : "";
      console.log(flag);
      console.log(visibleActive);
      console.log(visibleTransition);
    }, [flag]);