Ben Aston
Ben Aston

Reputation: 55729

How does the ref callback work in React?

The ref property enables us to capture the value of an uncontrolled component.

class MyComponent extends Component {
  render() {
     <input type="text" ref={el => this.setState({ myEl: el })}/>
  }
}

How does this work? Presumably input is actually a React component that has a property ("prop") ref that takes a callback that is invoked with the wrapper component of the field every when componentDidMount is called?

Upvotes: 4

Views: 4216

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

From the React documentation:

Adding a Ref to a DOM Element

React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

[...]

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

So the ref callback is called after the component is mounted to the DOM, with the underlying DOM element as the sole argument. It is also called after unmounting with the argument null.

Upvotes: 7

Related Questions