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?
From the React documentation:
Adding a Ref to a DOM Element
React supports a special attribute that you can attach to any component. The
refattribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.[...]
React will call the
refcallback with the DOM element when the component mounts, and call it withnullwhen 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.
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