I'm using this wrapper to detect clicks outside of a menu in order to open/close it. It kinda works but it bugs out when I click the button while it's open, the OnClickOutside
wrapper closes it, but then the button toggles it again (all in one click):
I wonder how can I fix that, here's how my components look:
import React from 'react';
import List from './list';
export default class ItemHeader extends React.Component {
constructor(props){
super(props);
this.state = {
showList: false
};
}
render() {
<div>
<button onClick = {this.toggleList.bind(this)}></button>
{this.renderList()}
</div>
}
renderList() {
let data = [1, 2, 3, 4, 5];
if (this.state.showList) {
return (
<List
data = {data}
toggleList = {this.toggleList.bind(this)}
/>
);
};
}
toggleList() {
if(!this.state.showList) {
this.setState({ showList: true });
} else this.setState({ showList: false });
}
}
And here's the list (that serves as a menu) component:
import React from 'react';
import OnClickOutside from 'react-onclickoutside';
export default class List extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data
};
}
render() {
return (
<ul>
{this.state.data.map(
(listItem, i) => <li key = {i}>{listItem}</li>
)}
</ul>
);
}
// Handle click away here:
handleClickOutside() {
this.props.toggleList();
}
}
export default OnClickOutside(List);