ReactJs Refs
Syntax
Refs provide a way to access DOM nodes or React elements created in the render method. It can be defined using the Ref
API as shown below:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myElement = React.createRef();
}
render() {
return <div ref={this.myElement}>...</div>;
}
}
Example
Let’s define a simple component and pass a ref to it.
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
console.log(this.myRef.current);
// Output: <div>Hello from MyComponent</div>
}
render() {
return <div ref={this.myRef}>Hello from MyComponent</div>;
}
}
Output
The output of the above example will log the div
element created in the render
method of the MyComponent
to the console.
Explanation
Refs are used for accessing the DOM nodes or React elements created in the render method. It provides a way to read and modify the values of an element. Once the ref is defined, it can be accessed using this.refName.current
.
In the above example, we create a ref for the div
element in the constructor method using React.createRef()
. This ref is then passed to the div
element using the ref
attribute, and the current
property of the ref is used to access the div
element in the componentDidMount
method.
Use
Refs can be used to access the instance of a component and modify its properties, or to access DOM nodes for purposes such as scrolling or selecting text.
Important Points
- Refs should be used sparingly, and only when necessary, as they break the encapsulation of the React component model.
- The
ref
attribute accepts a callback function instead of a string. This is generally more performant, especially when used with functional components. - When using refs with functional components, the ref must be defined using the
useRef
hook.
Summary
Refs provide a way to access DOM nodes or React elements created in the render method. They should be used sparingly and only when necessary. The ref
attribute is defined using the Ref
API, and the current
property is used to access the node or component instance. Refs are most commonly used for accessing the instances of components and modifying their properties, or for accessing DOM nodes for purposes such as scrolling or selecting text.