Reputation: 1029
I'm trying to make a menu that when it is clicked it shows up. This works fine. However I want the menu to close whenever anything but the original menu or item list is selected. When I do this however it returns with the error
Uncaught TypeError: _this.dropdownMenu.includes is not a function
at HTMLDocument.eval (FeedItem.jsx:277)
Visual
Code
import React, { Component } from 'react'
import styled from 'styled-components';
const OptionMenu = styled.div `
position: absolute;
top: 20px;
left: -130px;
display: ${props => props.showMenu ? 'flex' : 'none'};
flex-direction: column;
width: 150px;
background: #FFFFFF;
border: 1px solid #EEEFEF;
box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.12);
z-index: 100;
`;
const OptionItem = styled.div `
color: #414141;
font-size: 18px;
cursor: pointer;
padding: 10px 5px;
transition: .2s;
&:hover {
background-color: #F2F2F2;
}
`;
class FeedItem extends Component {
constructor() {
super();
this.state = {
showMenu: false
}
this.dropdownMenu = React.createRef();
}
showMenu = (e) => {
this.setState({ showMenu: true }, () => {
document.addEventListener('click', this.closeMenu);
});
}
closeMenu = (e) => {
if(!this.dropdownMenu.includes(e.target)) {
console.log('yes')
this.setState({ showMenu: false }, () => {
document.removeEventListener('click', this.closeMenu);
});
}
}
render(props) {
const { showMenu } = this.state;
return(
<Container item={this.props.id}>
<UserOptions onClick={() => this.showMenu()} ref={this.dropdownMenu}>
<OptionMenu showMenu={showMenu}>
<OptionItem>Share</OptionItem>
<OptionItem>Something</OptionItem>
</OptionMenu>
</UserOptions>
</Container>
);
}
}
export default FeedItem;
I'm using styled-components could this be an issue? Also I've delted most of the parts of the container and have just left the problem areas.
Upvotes: 4
Views: 16952
Reputation: 112787
includes
is a String
and Array
method, not a Node
method.
You can use contains
instead:
closeMenu = (e) => {
if (!this.dropdownMenu.current.contains(e.target)) {
console.log('yes')
this.setState({ showMenu: false }, () => {
document.removeEventListener('click', this.closeMenu);
});
}
}
Upvotes: 2