Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't react disable the onClick handler when disabled is true?

I would expect that setting the disabled attribute on a react component would block the onClick handler for that element.

 <a role="button"
        className={`btn btn-block btn-info`}
        disabled={!this.state.readyToView}
        href={this.state.selectedObjectLink}
        onClick={this.handleLink}
        >View</a>

but although the element shows a "disabled" attribute it still registers a click event.

Edit: I should clarify - I handle the click event in handleLink, I want to know why the disabled attribute doesn't remove the handler? Sorry for any confusion.

like image 672
Liz Avatar asked Jan 11 '17 07:01

Liz


1 Answers

The problem isn't with disabled; it's with the HTML element a. Anchor <a> cannot have a disabled property (what does that even mean?). Just because you've passed CSS to make the element look like a button, doesn't make it a button. It is still an anchor.

The solution would be either to use something else (like button):

<button 
  role="button"
  className={`btn btn-block btn-info`}
  disabled={!this.state.readyToView}
  onClick={this.handleLink}
>
  View
</button>

You can use this.state.selectedObjectLink inside handleLink if you want to redirect to a page

Or use one of the many other suggestions on this page.

like image 172
Kousha Avatar answered Nov 15 '22 22:11

Kousha