What are refs in React? When should they be used?
Refs provide a way to access DOM nodes or React elements created in the render method. Refs should be used sparingly, but there are some good use cases for refs, such as:
Managing focus, text selection, or media playback.
Triggering imperative animations.
Integrating with third-party DOM libraries.
Refs are created using React.createRef()
method and attached to React elements via the ref attribute. In order to use refs throughout the component, assign the ref to the instance property within the constructor.
Code Sample:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
render() {
return <div ref={this.myRef} />
}
}
- Refs can also be used in functional components with the help of closures.
- Refs are used to return a reference to an element.
- Refs shouldn't be overused.
You can create a ref using React.createRef()
and attach to elements via the ref
attribute.
Note: Avoid using refs for anything that can be done declaratively.
For example, instead of exposing open()
and close()
methods on a Dialog component, pass an isOpen
prop to it.
How to access 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;
Thanks for reading...
Happy Coding!