0

I have a tag that has onClick property. How can I remove the event from the tag using jQuery? is that even possible?

2
  • 2
    please don't mix jQuery and react as jQuery makes changes directly to the dom while react re renders when the dom's changed and they will shout at each other and you will not end up well. Can't you just remove the onClick from the react code instead? I think you will get better of that way tbh. Commented Aug 3, 2017 at 15:48
  • @LucasReppeWelander. I agree with you it is not even possible. Commented Aug 3, 2017 at 16:10

2 Answers 2

1

Oh the answer above gave me idea so instead of overriding the component prop, override the event instead.

<button onClick={this.props.handleClick}>click me</button>

var elem = $('.yourbutton');
elem.click(() => { return false }); 
Sign up to request clarification or add additional context in comments.

Comments

0

No, it isn't possible. You can add a new event and then stop propagation but it's hacky. jQuery cannot remove events it does not own.

if the component composes props, you can override it or add onClickCapture={e => e.stopPropagation()}

eg if your component allows you to pass props, even if onClick is after the prop spread, you can still do it via the capture phase of the event which fires before the handler:

class Foo extends React.Component {

  handleClick(e){
    console.info(e)
  }

  render(){
    return <button {...this.props} onClick={this.handleClick}>click me</button>
  }
}

const app = document.getElementById('app')
ReactDOM.render(<Foo onClickCapture={e => e.stopPropagation()} />, app)

https://jsfiddle.net/tdbs7h05/

Otherwise, you can read the source code and "hack it" by changing the prototype of the component. For example:

class Foo extends React.Component {

  handleClick(e){
    console.info(e)
  }

  render(){
    return <button onClick={this.handleClick}>click me</button>
  }
}

const app = document.getElementById('app')
Foo.prototype.handleClick = (e) => e.preventDefault() || e.stopPropagation()
ReactDOM.render(<Foo />, app)

1 Comment

Yes I have to admit it is hacky and not recommended. If it is not possible then I will just disable it on the component level and not using jquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.