reactjsonfocus

How can focus events filtered out coming from select item changes?


focus events are listened, component is notified when browser / page is opened again:

    useEffect(() => {
        //Add a listener on the window object
        window.addEventListener('focus', onFocus)

        //Clean listeners
        return () => {
            window.removeEventListener('focus', onFocus)
        }
    }, [])

    const onFocus = (e) => {
        if (e.) { // <--------------
            return
        }
        dispatch(
            log({
                text: 'onFocus get called',
            })
        )
        callBuyTicket2()
    }

But selecting other option in select item on the page will fire also focus event. Is it a way to filter those events out?

enter image description here


Solution

  • I think you have to use a state and the onblur event.

    const [isCurrentlyInPage, setIsCurrentlyInPage] = useState(true)
    useEffect(() => {
        //Add a listener on the window object
        window.addEventListener('focus', onFocus)
        window.addEventListener('blur', onBlur)
    
        //Clean listeners
        return () => {
            window.removeEventListener('focus', onFocus)
            window.removeEventListener('blur', onBlur)
        }
    }, [])
    
    const onFocus = (e) => {
        if(!isCurrentlyInPage){
            setIsCurrentlyInPage(true)
            //your code
        }
    }
    
    const onBlur = () => {
        setIsCurrentlyInPage(false)
    }