How to create Refs?
There are three main ways to make refs in React. Starting with the oldest, here is a list of the various methods:
- String references (legacy method)
String refs are the standard means of creating refs in a React application. This is the oldest approach and is considered legacy or deprecated because it will be removed in future React releases.
String refs are easily created by adding a ref prop to the desired element and setting the value to a string name for the ref. Here's an example:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.toggleInputCase = this.toggleInputCase.bind(this);
this.state = { uppercase: false };
}
toggleInputCase() {
const isUpper = this.state.uppercase;
// Accessing ref using this.refs.inputField
const value = this.refs.inputField.value;
this.refs.inputField.value =
isUpper
? value.toLowerCase()
: value.toUpperCase();
this.setState({ uppercase: !isUpper });
}
render() {
return (
<div>
{/* Create a string ref named: inputField */}
<input type="text" ref="inputField" />
<button type="button" onClick={this.toggleInputCase}>
Toggle Case
</button>
</div>
);
}
}
Instead of giving the ref's name as a string, callback refs employ a callback function to create them. This should be your preferred method of establishing refs if you're using React versions prior to version 16.3.
The React component instance or the HTML DOM element is passed as an argument to the callback method, which can be kept and accessed elsewhere. Our previous code snippet will be transformed into the following using a callback ref.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.toggleInputCase = this.toggleInputCase.bind(this);
this.state = { uppercase: false };
}
toggleInputCase() {
const isUpper = this.state.uppercase;
// Accessing the ref using this.inputField
const value = this.inputField.value;
this.inputField.value =
isUpper
? value.toLowerCase()
: value.toUpperCase();
this.setState({ uppercase: !isUpper });
}
render() {
return (
<div>
{/* Create a callback ref and store it in this.inputField */}
<input type="text" ref={elem => this.inputField = elem} />
<button type="button" onClick={this.toggleInputCase}>
Toggle Case
</button>
</div>
);
}
}
- 'React.createRef' (from React 16.3)
Since React 16.3, the React API has provided a createRef() method that can be used to create refs in the same way that the callback function could be used. You simply call React.createRef() to create a ref and then assign it to an element.
Here's what our previous example would look like if we used React.createRef():
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputField = React.createRef();
this.toggleInputCase = this.toggleInputCase.bind(this);
this.state = { uppercase: false };
}
toggleInputCase() {
const isUpper = this.state.uppercase;
// Accessing the ref using this.inputField.current
const value = this.inputField.current.value;
this.inputField.current.value =
isUpper
? value.toLowerCase()
: value.toUpperCase();
this.setState({ uppercase: !isUpper });
}
render() {
return (
<div>
{/* Reference the ref from this.inputField */}
<input type="text" ref={this.inputField} />
<button type="button" onClick={this.toggleInputCase}>
Toggle Case
</button>
</div>
);
}
}
- The 'useRef' Hook (from React 16.8)
The Hooks API has become the de facto way of abstracting and reusing code in React apps since its release in React v16. useRef is an example of a Hook that allows us to build and use refs in functional components.
Since we can't construct instances of functions, even with the useRef Hook, you can't use the ref attribute on functional components by default.
To use the useRef Hook, simply call it and supply it the object that ref.current should refer to. This Hook call should return a ref object, which we can use in the same way as the createRef method.
const MyComponent = () => {
const [uppercase, setUppercase] = React.useState(false)
const inputField = React.useRef(null)
const toggleInputCase = () => {
// Accessing the ref using inputField.current
const value = inputField.current.value;
inputField.current.value = uppercase ? value.toLowerCase() : value.toUpperCase();
setUppercase(previousValue => !previousValue)
}
return(
<div>
{/* Reference the ref from this.inputField */}
<input type="text" ref={inputField} />
<button type="button" onClick={toggleInputCase}>
Toggle Case
</button>
</div>
);
}
}
Access React Refs
When a ref is supplied to an element inside a render method in React, the current attribute of the ref can be used to get a reference to the node.
const node = this.callRef.current;
What is ReactDOM?
ReactDOM is a package that provides DOM-specific methods that may be used at the top level of a web application to efficiently control the web page's DOM elements. The following methods are available for developers in ReactDOM's API:-
- render()
- findDOMNode()
- unmountComponentAtNode()
- createPortal()
- hydrate()
Prerequisites for ReactDOM
To use ReactDOM in a React website or application, we must first import it from the react-dom package using the code snippet below:
import ReactDOM from 'react-dom';
Refs: Uncontrolled Components
Since React is responsible for handling updates to the component when form data changes, all components in React are controlled by default.
Refs come in helpful when dealing with uncontrollable components in React. This is because you rely on refs to acquire form values from the DOM rather than event handlers to update the state when the form data changes.
Frequently Asked Questions
- What do you mean by React Refs?
Ans: In React, the shorthand for references is called 'refs' refs are similar to keys. It is a property that allows you to save a reference to specific DOM nodes or React elements. It simply allows us to access React DOM nodes or React elements and interact with them. It is used when we don't want to use props when updating the value of a child component.
2. When is it required to use Refs?
Ans: There are a couple of good uses for refs:
- Focus, text selection, and media playing can all be managed.
- Imperative animations are triggered.
- Third-party DOM libraries also are integrated.
- It can be used in callbacks.
Do not use refs for something that can be done declaratively. Refs should not be used with functional components as they lack instances.
Instead of using open() and close() methods on a Dialog component in React, use the 'isOpen' property instead.
3. Define the current properties of Refs?
Ans: The ref value varies depending on the node type:
- The ref is created using React.createRef() when the ref attribute is utilised in an HTML element. The current property of React.createRef() is the underlying DOM element.
-
If a custom class component has the ref attribute, the ref object receives the mounted instance of the component as its current property.
- The function components do not have instances, so the ref attribute can't be used on them.
4. What are the issues related to callback refs?
Ans: The issue with callback refs is that if the callback ref is an inline function, it will be called twice during updates, once with null and once with the DOM element. Because each render creates a new instance of the function, React needs to clear the old ref and set up the new one. We can avoid this by making the callback ref a bound method on the class, but in most circumstances, this isn't necessary.
Key Takeaways
In this blog, we went over the fundamentals of React refs and dom. We also considered various techniques in which we will be able to interact with the react refs and DOM in a react application. We also learned how to use the new 'React.createRef()' and 'useRef' Hook, which React introduced to simplify the process of creating Refs.
Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of React refs and dom in Web Development.
Credits: GIPHY
Happy Developing!