Abhishek Roy
Abhishek Roy

Reputation: 75

how do i toggle the div when click outside of the button in react js?

here in my code i m toggling a panel on the basis of click event when clicked it will show and when again clicked on the same button it will disappear. but what i want when i will click outside the button anywhere the panel should close, how do i do that?

function Project(props) {
    const [rightPanel, setrightPanel] = useState(false);

    function projectToggle () {
        if(!rightPanel) setrightPanel(true);
        else setrightPanel(false);
        }
    return (
        <React.Fragment>
            <div className="vh-ce-align pd-b-10 mg-b-5 bo-bottom-grey">
                <div className="button-blue" onClick={projectToggle}>Create New Project</div>
            </div>
            <div className="d-flex">
                
                {rightPanel ? (<div className="right-side-panel">
                    <div className="mg-b-20">
                        <div className="fw-bold mg-b-10">Client Id</div>
                        <input type="text" className="right-side-input"/>
                    </div>
                    <div className="mg-b-20">
                        <div className="fw-bold mg-b-10">Frequency</div>
                        <div className="wd-pct-100 d-flex pd-b-5 bo-bottom-grey">
                            <div className="flex-one">Annually</div>
                            <i className="fas fa-chevron-down mg-r-10"></i>
                        </div>
                    </div>
                    <div className="mg-b-20">
                        <div className="fw-bold mg-b-10">Year</div>
                        <div className="wd-pct-100 d-flex pd-b-5 bo-bottom-grey">
                            <div className="flex-one">Select Year</div>
                            <i className="fas fa-chevron-down mg-r-10"></i>
                        </div>
                    </div>
                </div>): null}
            </div>
        </React.Fragment>
    )
}

Upvotes: 1

Views: 1568

Answers (2)

Dae Hyeon Mun
Dae Hyeon Mun

Reputation: 536

Try this code below.

const handleClickClosePanelFromOutside = (e) => {
    if (e.target.className !== "button-blue") {
        setRightPanel(false);
    }
}

useEffect(() => {
    document.body.addEventListener("click", handleClickClosePanelFromOutside)
    return () => {
        document.body.removeEventListener("click", handleClickClosePanelFromOutside)
    }
})

Upvotes: 1

Joe Johnson
Joe Johnson

Reputation: 1824

What you're looking for is an event type to attach an event handler function to ... And, in this case, the not so obvious answer is a blur (opposite of focus) event. When anything in the DOM observes a user interaction after the button is clicked, the button will receive an onblur event.

Upvotes: 0

Related Questions