CodesJava

Easy learning with example program codes

Refs in ReactJS

React Refs
Refs are the shorthand, similar to the React keys. They are used for references in React, to store a reference to particular DOM nodes or React elements, to access React DOM nodes or React elements, to interact with React DOM nodes or React elements and to change the value of a child component, without using props.

Thus it can be used when we need DOM measurements or if there is a need to trigger imperative animations. It can also be used while integrating with third-party DOM libraries and in callbacks. However, its use should be avoided for declarative actions and for overuse purposes.

Creating Refs:
React.createRef() method is used to create React Ref.

Code:

class MyComponent extends React.Component {  
constructor(props) {  
super(props);  
this.callRef = React.createRef();  
}  
render() {  
return <div ref={this.callRef} />;  
}  
}

Accessing Refs:
A reference to the node can be accessed via the current attribute of the ref when a ref is passed to an element inside the render method in ReactJs.

Code:

const node = this.callRef.current;

Current Properties of the React Ref:

  • Depending on the type of the node, the value of the ref can differ.
  • The underlying DOM element is received as its current property, by the ref created with React.createRef(), when the ref attribute is used in HTML element.
  • The mounted instance of the component is received as its current property, by the ref object, if the ref attribute is used on a custom class component.
  • The ref attribute doesn’t have instances, and thus they cannot be used on function components.

Example: Adding Ref to DOM elements.

import React, { Component } from 'react';  
import { render } from 'react-dom';  
class App extends React.Component {  
constructor(props) {  
super(props);  
this.callRef = React.createRef();  
this.addingRefInput = this.addingRefInput.bind(this);  
}  
addingRefInput() {  
this.callRef.current.focus();  
}  
render() {  
return (  
<div>  
<h1>Hello World</h1>  
<input  
type="text"  
ref={this.callRef} />  
<input  
type="button"  
value="Enter text"  
onClick={this.addingRefInput}  
/>  
</div> 
);  
}  
}  
export default App;

Output:

Explanation:
Here, a ref is added to store the reference to a DOM node or element.

Example: Adding Ref to Class components

import React, { Component } from 'react';  
import { render } from 'react-dom';  
function CustomText(props) {  
let callRefInput = React.createRef();  
function ClickAction() {  
callRefInput.current.focus();  
}  
return (  
<div>  
<h1>Hello World</h1>  
<input  
type="text"  
ref={callRefInput} />  
<input  
type="button"  
value="Click Me"  
onClick={ClickAction}  
/>  
</div> 
);  
}  
class App extends React.Component {  
constructor(props) {  
super(props);  
this.callRefInput = React.createRef();  
}  
focusRefInput() {  
this.callRefInput.current.focus();  
}  
render() {  
return (  
<CustomText ref={this.callRefInput} />  
);  
}  
}  
export default App;

Output:

Explanation:
Here, a ref is added to store the reference to a class component.

Callback refs:
Callback refs is another way to use refs in ReactJS, which gives more control when the refs are set and unset.

Example: To create refs by passing a callback function to the ref attribute of a component.

<input type="text" ref={element => this.callRefInput = element} />

Example: To access the reference to the DOM node stored in an instance property.

this.callRefInput.value

Example: Working of the CallbackRefs.

import React, { Component } from 'react';  
import { render } from 'react-dom';     
class App extends React.Component {  
constructor(props) {  
super(props);  
this.callRefInput = null;  
this.setInputRef = element => {  
this.callRefInput = element;  
};  
this.focusRefInput = () => {  
if (this.callRefInput) this.callRefInput.focus();  
};  
}  
componentDidMount() {  
this.focusRefInput();  
}  
render() {  
return (  
<div>  
<h1>Hello World</h1>  
<input  
type="text"  
ref={this.setInputRef}  
/>  
<input  
type="button"  
value="Click Me"  
onClick={this.focusRefInput}  
/>  
</div>  
);  
}  
}  
export default App;

Output:

Explanation:
When the component mounts, the “ref” callback will be called to store the reference to the input DOM element. When the component unmounts, the React will call it with null. Before the firing of the componentDidMount or componentDidUpdate, Refs will be always up-to-date.

Forwarding Ref from one component to another component:
The React.forwardRef() method is used to perform the technique of Ref forwarding, which is used for passing a ref through a component to one of its child components, especially for higher-order components and reusable component libraries.

Example:

import React, { Component } from 'react';  
import { render } from 'react-dom';  
const X = React.forwardRef((props, ref) => (  
<input type="text" placeholder="Welcome" ref={ref} />  
));  
const Y = React.createRef(); 
class CustomX extends React.Component {  
handleSubmit = e => {  
e.preventDefault();  
console.log(Y.current.value);  
};  
render() {  
return (  
<div>  
<form onSubmit={e => this.handleSubmit(e)}>  
<X ref={Y} />  
<button>Submit</button>  
</form>  
</div>  
);  
}  
}  
export default App;

Explanation:
Here, the X is a component, that has a child as an input field. The process flow to pass or forward the ref down to the input is like; creating a ref; passing the ref down to X ref={Y} forwarding the ref to the forwardRef function as a second argument by React; forwarding the ref argument down to input ref={ref} and ultimately accessing the value of the DOM node at Y.current.

React with useRef():
To get access to the DOM node or element, useRef() method was introduced in React 16.7 and above version. It was necessary to interact with any DOM node or element. The ref object is returned whose .current property is initialized to the passed argument, and it persists for the lifetime of the component.

Syntax:

const refContainer = useRef(initialValue);

Example:

function Example() {  
const Y= useRef(null);  
const X = () => {  
Y.current.focus();  
};  
return (  
<>  
<input ref={Y} type="text" />  
<button onClick={X}>Submit</button>  
</>  
);  
}

Explanation:
The useRef function is assigned to the variable Y which is then attached to the ref attribute, inside the HTML element to reference.

Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status