Remove Jquery EventListener react.js

2

I am working on a project using react.js, I have a component called chatBox which I am using in different components, as shown in the example.

The problem that arises is that every time I render a component the click event is duplicating. Is there a way to do a removeEventListener when the component is removed?

var ChatBox = React.createClass({
    componentDidMount(){
      $('.addPrivate').on('click', function(){

      })
    },
    componentWillunMount(){
      console.log('removeEventListener')
    },
    render(){
      return <div>Chat <a href="javascript:;" className="addPrivate">Click</a></div>
    }
})

var Home = React.createClass({
    render(){
      return <div>
             <chatBox />
      </div>
    }
})

var Profile = React.createClass({
    render(){
      return <div>
             <chatBox />
      </div>
    }
})
    
asked by DANIEL LUCUMI 26.10.2016 в 23:35
source

2 answers

1

The problem is that if you use the same component more than once, you will have more than one element with class='addPrivate'

<a href="javascript:;" className="addPrivate">Click</a>

The correct thing would be to use the handler directly in the element

var ChatBox = React.createClass({
    onClick(event) { ... },
    render(){
      return <div>Chat <a href="javascript:;" onClick={this.onClick}>Click</a></div>
    }
})

You should not be manipulating DOMObjects directly if you use react.

    
answered by 28.10.2016 в 14:33
0

How about using off .

function onClickHandler() { ... };

... 

componentDidMount(){
  $('.addPrivate').on('click', onClickHandler)
},
componentWillUnmount(){
  $('.addPrivate').off('click', onClickHandler)
}

Salu2

    
answered by 26.10.2016 в 23:43