Anitta Paul
Anitta Paul

Reputation: 465

Close component on outside click- reactjs

I am building something like this in reactJs.

<div className={'stories-outer'}> //div #1
    <div>  //div #2
        ...
    <div/>
</div>

I want to close the component on clicking anywhere ouside div #2.

I tried it using onBlur property like this:

<div className={'stories-outer'} onBlur={()=>showComponent(false)} tabIndex='0'> //div #1
    <div>  //div #2
        ...
    <div/>
</div>

But was not working.

I also tried using onClick like this:

<div className={'stories-outer'} onClick={()=>showComponent(false)}> //div #1
    <div>  //div #2
        ...
    <div/>
</div>

But the component was closed on clicking inside div #2 also, which should not happen. Please share a solution. Thank you :)

Upvotes: 0

Views: 67

Answers (1)

Muhammed B. Aydemir
Muhammed B. Aydemir

Reputation: 1015

Sounds like you seek the event.stopPropagation method.

Example:

<div className={'stories-outer'} onClick={()=>showComponent(false)}> //div #1
    <div onClick={(event) => event.stopPropagation()}>  //div #2
        ...
    <div/>
</div>

Upvotes: 1

Related Questions