Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manipulate attributes from ref selector

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')
like image 646
ThomasReggi Avatar asked Sep 10 '15 15:09

ThomasReggi


2 Answers

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')
like image 135
cybergrind Avatar answered Sep 30 '22 18:09

cybergrind


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>
  )
}
like image 29
Jim O'Brien Avatar answered Sep 30 '22 16:09

Jim O'Brien