Reputation: 1674
I am trying to show/hide a component based on its state and I want to change it on a click in a 3rd component.
//navbar
export class NavigationBar extends React.Component {
constructor(props) {
super(props);
this.state = {
showNotification: false,
}
}
handleNotification = () => this.setState({
showNotification: !this.state.showNotification,
});
{ this.state.showNotification ? <Outside><Notifications /></Outside> : null}
//outside component, responsible for detect if a click happened outside it.
export default class Outside extends Component {
constructor(props) {
super(props);
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside)
}
setWrapperRef(node) {
this.wrapperRef = node;
}
handleClickOutside(event) {
if(this.wrapperRef && !this.wrapperRef.contains(event.target)) {
console.log("clicked outside notifications");
this.setState({
showNotification: false
})
}
}
render() {
return (
<div ref={this.setWrapperRef}>
{this.props.children}
</div>
)
}
}
Outside.propTypes = {
children: PropTypes.element.isRequired
}
My doubt is how can I change the state in navbar based on the event that is being detected inside Outside component
?
Upvotes: 0
Views: 67
Reputation: 525
In parent, you need downward to Outside a event handler:
<Outside toggleNofitication={this.handleNotification}><Notifications /></Outside>
and in Outside, just call toggleNofitication
when event fired:
handleClickOutside = () => {
// ...
this.props.toggleNofitication()
}
Upvotes: 2