smilebuz
smilebuz

Reputation: 377

How to add ref for react element (node reactNode!)

I want to add ref to a react element. combox

Now I can reach this by this.refs.combox, but findDOMNode gives a error, I want to add a ref to this element in so I can reach it later using this.refs.combox. Anyone can help? thanks!

Updated: Here's my render function. Now I simply surround the combox with a div. I wonder if I could add a ref directly to the combox and don't need to add a div around it.

render function

Upvotes: 2

Views: 6947

Answers (1)

Shahriat Hossain
Shahriat Hossain

Reputation: 340

Creating Refs Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

Accessing Refs When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

const node = this.myRef.current;

The value of the ref differs depending on the type of the node:

When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current. You may not use the ref attribute on functional components because they don’t have instances.

The examples below demonstrate the differences.

Adding a Ref to a DOM Element This code uses a ref to store a reference to a DOM node:

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />

        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

React will assign the current property with the DOM element when the component mounts, and assign it back to null when it unmounts. ref updates happen before componentDidMount or componentDidUpdate lifecycle hooks.

Upvotes: 1

Related Questions