To React from jQuery: Disable a Button

The Setup

We have ourselves a React component with a login form for our brand new app. It works nicely. It even has an error warning for a pleasant UX. How wonderful, one might exclaim!

Login Form with a returned warning

But Not so Fast

An issue quickly rears its ugly head: the user can click the login button multiple times. And often, people do just that. They will tap a button a few times to make sure it’s working, and working fast! (Hey, I’ve done that).

Needless to say, this tapping or clicking can wreck havoc on the system: sending multiple requests for authentication, getting un-synced warnings, and giving a confusing experience to the user. How can one tolerate this ugliness? Non.

DOM Manipulation

Well, simple enough! Just disable the button after the user clicks it. We have a perfectly good HTML property for this purpose!

<button disabled>Login</button>

And we can control the disabled property with some hot DOM manipulation techniques:

$('button').prop('disabled', true);
$('button').prop('disabled', false);

Yup, we’d need much better CSS selectors, but that’s the idea: whip out jQuery to change the state of this button when we need to.

The state of this button. Wait, the state! React! I don’t want to keep track of this button in the DOM, like what the best selectors might be to find it, what the class names are. I also have to make sure those selectors and names remain relevant as I keep developing.

What I want is to say that disabled is true or false for this button, and not worry about the implementation of the consequences. While I’m fetching my auth results, disabled is true; otherwise it’s not. End of thinking.

Show us React, then

We have state! So, instead of loading jQuery, let us add a disabled state to our lonesome React component.

getInitialState : function() {
return {
disabled: false

In the render method, we can tack on our trusted disabled HTML property conditionally, with a ternary statement here:

render: function(){ 
var disabled = this.state.disabled ? 'disabled' : ''
return (
// stuff
<button {disabled}>Login</button>

and boom, all we have to think about is the state. No more thinking about and remembering DOM nodes that can be dangerously slow to touch directly.

Now, when I do call my auth function (and later its callback), I set the state as I wish, and let React take over with all its built-in awesomeness.

this.setState({ disabled: true });

Its easier to think about, isn’t it?

What do you reckon? How would you reason this in Angular?

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.