4

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):

enter image description here

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);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vlady Veselinov
  • 4,678
  • 5
  • 23
  • 49
  • 2
    you need to `stopPropagation` on the button click to prevent the event from passing up to the next handler. meaning in your toggleList you need to accept the event in the function arguments. `toggleList(e){ e.stopPropogation();` – John Ruddell May 02 '16 at 03:22
  • 2
    This is not react specific this is a basic javascript feature. event bubbling happens on a child to parent that both have an event like a click. you can prevent that bubbling from that – John Ruddell May 02 '16 at 03:24
  • 1
    Oh jeez... I just found out that the onOutsideClick wrapper I'm using has a feature that lets you ignore certain elements... I just added a "ignore-react-onclickoutside" on the button and it worked! Thank you for the info, I didn't know about stopPropagation. – Vlady Veselinov May 02 '16 at 03:27

0 Answers0