React.createRef
Added in 16.3
Refs provide a way to access DOM nodes or React elements created in the render method.
In the typical React dataflow, props are the only way that parent components interact with their children.
To modify a child, you re-render it with new props.
There are a few cases where you need to imperatively modify a child outside of the typical dataflow.
The child to be modified could be an instance of a React component, or it could be a DOM element.
For both of these cases, React provides an escape hatch.
Common Uses
(1) Managing focus, text selection, or media playback.
(2) Triggering imperative animations.
(3) Integrating with third-party DOM libraries.
Avoid using refs for anything that can be done declaratively.
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} />;
}
}
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;
link - legacy.reactjs.org/docs/refs-and-the-dom.html
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext