I'd like to add a disabled
attribute to the element that has ref="formButton"
, I tried this and it didn't seem to work:
React.findDOMNode(this.refs.formButton).attr('disabled')
this.refs.formButton.attr('disabled')
Use standard DOM API for this, like:
React.findDOMNode(this.refs.formButton).setAttribute('disabled', true)
Or, if you want to use jquery:
$(React.findDOMNode(this.refs.formButton)).attr('disabled')
The 'React' way of doing this is to control the button's disabled
attribute in the render method, and using the component's state to keep track of it.
For example:
var myComponent = React.createClass({
getInitialState: function() {
return { disabled: false };
},
disableFormButton: function() {
this.setState({ disabled: true });
},
render() {
return (
<div>
...
<button
disabled={this.state.disabled}
onClick={this.disableFormButton.bind(this)}>
Disable
</button>
</div>
);
}
});
JSFiddle here
Note that you no longer need the ref
, as you don't need to access the DOM node from outside the render
method.
See Thinking in React from the React.js documentation for more information about what should be stored in a component's state, and what should be passed as properties.
For those reading in 2020 and later
Since the introduction of the Hooks API in React, you can rewrite the example here using a functional component.
const myComponent = () => { const [disabled, setDisabled] = React.useState(false) return ( <button disabled={disabled} onClick={() => setDisabled(true)}> Disable </button> ) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With