Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the state when clicking outside a component in React

I have a dropdown as is shown in the following image: enter image description here

When I click the folder icon it opens and closes because showingProjectSelector property in the state that is set to false.

  constructor (props) {
    super(props)
    const { organization, owner, ownerAvatar } = props
    this.state = {
      owner,
      ownerAvatar,
      showingProjectSelector: false
    }
  }

When I click the icon, it opens and closes properly.

<i
  onClick={() => this.setState({ showingProjectSelector: !this.state.showingProjectSelector })}
  className='fa fa-folder-open'>
</i>

But what I'm trying to do is to close the dropdown when I click outside it. How can I do this without using any library?

This is the entire component: https://jsbin.com/cunakejufa/edit?js,output

like image 755
Liz Parody Avatar asked Feb 07 '18 22:02

Liz Parody


1 Answers

You could try leveraging onBlur:

<i onClick={...} onBlur={() => this.setState({showingProjectSelector: false})}/>
like image 167
Arman Charan Avatar answered Nov 14 '22 22:11

Arman Charan