OnClick events won't run without double clicking the element - Next.js SSG

Viewed 20

Everything with an onClick event listener won't run unless clicked for a second time. I believe it has something to do with the state not updating on the first click, but I'm at a loss on how to fix this.

I'm using getStaticProps() on each page for SSG which could have something to do with this. Here's an example of one of the events:

export default function Dropdown({ children, text}){
    const [open, setOpen] = useState(false)
    
    const handleClick = (e)=>{
        e.preventDefault()
           setOpen(!open)
    }
 


    return(
        <>
        <div className="relative w-full h-full" >
            <div  className="inline-flex rounded-md">
                    <button type="button"
                            onClick={(e)=>handleClick(e)}
                            className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 bg-white hover:text-gray-700 focus:outline-none transition">
                            {text}
                        <svg
                            className="ml-2 -mr-0.5 h-4 w-4"
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 20 20"
                            fill="currentColor"
                        >
                            <path fillRule="evenodd"
                                  d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                                  clipRule="evenodd"/>
                        </svg>
                    </button>
            </div>
            <AnimatePresence>
                {open
                    ?
                    <motion.div
                        initial={{opacity: 0, scale: 0.95}}
                        animate={{opacity: 1, scale:1}}
                        exit={{opacity: 0, scale: 0.95}}
                        transition={{ease: 'easeInOut', duration: 0.2}}
                        className={`w-fit origin-top absolute z-50 mt-2 right-0 bg-white top-6 rounded-md shadow-lg`}
                        onMouseLeave={()=>{setOpen(false)}}
                    >
                        <div className={`rounded-md ring-1 ring-black ring-opacity-5`} >
                            {children}
                        </div>
                    </motion.div>

                    :<></>

                }
            </AnimatePresence>
        </div>
        </>
    )
}

I'd appreciate any insight I can get on this. I've tried dynamic imports as well and that didn't fix anything.

I've only been working with React and Next for a couple years now, but nothing like this has occurred before.

1 Answers

You can try

setOpen(prevState => !prevState)

So your setState action will know that has to update the current value

Related