The ref
property enables us to capture the value of an uncontrolled ponent.
class MyComponent extends Component {
render() {
<input type="text" ref={el => this.setState({ myEl: el })}/>
}
}
How does this work? Presumably input
is actually a React ponent that has a property ("prop") ref
that takes a callback that is invoked with the wrapper ponent of the field every when ponentDidMount
is called?
The ref
property enables us to capture the value of an uncontrolled ponent.
class MyComponent extends Component {
render() {
<input type="text" ref={el => this.setState({ myEl: el })}/>
}
}
How does this work? Presumably input
is actually a React ponent that has a property ("prop") ref
that takes a callback that is invoked with the wrapper ponent of the field every when ponentDidMount
is called?
-
3
BTW don't mutate state directly! Use
setState
– Andrew Li Commented Jun 23, 2017 at 12:45
1 Answer
Reset to default 7From the React documentation:
Adding a Ref to a DOM Element
React supports a special attribute that you can attach to any ponent. The
ref
attribute takes a callback function, and the callback will be executed immediately after the ponent is mounted or unmounted.[...]
React will call the
ref
callback with the DOM element when the ponent mounts, and call it withnull
when it unmounts.
So the ref
callback is called after the ponent is mounted to the DOM, with the underlying DOM element as the sole argument. It is also called after unmounting with the argument null
.