0

I have:

showDropdown(e) {
        e.preventDefault();

        document.addEventListener('click', this.closeDropdown);
        this.setState({activeDropdown: "Only_show"})
    }

    closeDropdown() {
        document.removeEventListener('click', this.closeDropdown);
    }
...

<DropdownMenu text="New" count={127}/>
                    <DropdownMenu text="Only show"
                                  isOpen={this.state.activeDropdown === "Only_show"}
                                  onClick={this.showDropdown.bind(this)}>
                        <li>New</li>
                        <li>Old</li>
                    </DropdownMenu>
...

Dropdown.js

import React, {Component} from 'react';

export default class DropdownMenu extends Component {

    constructor(props) {
        super(props);

        this.state = {
            highlight: false,
            count: this.props.count || 0,
            selection: null
        }
        this.showDropdown = this.showDropdown.bind(this);
        this.selectItem = this.selectItem.bind(this);
    }

    componentDidMount() {

    }

    selectItem(e) {

    }

    render() {
        return <div className="dropdown__menu" onClick={this.props.onClick}>
            {this.props.text} {this.state.count > 0 ? <b>{this.state.count}</b> : ''}
            <div className="dropdown__content"
                 style={this.props.isOpen ? {'display': 'block'} : {'display': 'none'}}>
                {this.props.children}
            </div>
        </div>
    }
}

What am I doing wrong?

imperium2335
  • 23,402
  • 38
  • 111
  • 190
  • 1
    To *open* the dropdown, you're using this click handler: `onClick={this.showDropdown.bind(this)}` That suggests you aren't binding these in the constructor (which you might want to consider doing, rather than on every render). But with your document click handler, you're not doing that, so `this` is incorrect. Since you need to remove the handler, binding in the constructor is probably your best bet: `this.closeDropdown = this.closeDropdown.bind(this);` – T.J. Crowder Feb 14 '19 at 08:16
  • 1
    Nice one! Thank you, make it an answer. – imperium2335 Feb 14 '19 at 08:23
  • :-) It's covered by the duplicate. But I like to do a comment to make clear why I think the duplicate is useful, e.g., how it relates to your specific situation. Happy coding! – T.J. Crowder Feb 14 '19 at 16:24

0 Answers0