Skip to content

Spoke Right

Education for everyone

https://spokeright.com
Primary Menu
  • Home
  • Our Services
    • Translation
    • Interpretation
    • Transcription
    • Voice-Over
    • Proofreading
    • Content writing
  • Free Education
    • Learn Android Studio
    • Learn Python
    • Learn MongoDB
    • Learn MySql
    • Learn React
    • Montessori Education
  • Spoke Right News
  • Earn Online
  • Classic Games by Spoke Right
    • TicTac
    • Checkers
    • Foosball
    • Billiards
    • Master Chess
    • Logic Game
  • Contact Us
Download Now
  • Home
  • Learn React
  • How do you use refs in React
  • Learn React

How do you use refs in React

Spoke Right December 13, 2022 4 min read

Refs In React

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;

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;

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.

Continue Reading

Previous: How do you give keys in React
Next: What are fragments in React JS

Related Stories

Which is Difference Between AngularJS And ReactJS
1 min read
  • Learn React

Which is Difference Between AngularJS And ReactJS

December 16, 2022
What is higher-order component in Reactjs
2 min read
  • Learn React

What is higher-order component in Reactjs

December 16, 2022
How do I create a table in ReactJS
2 min read
  • Learn React

How do I create a table in ReactJS

December 16, 2022

This AD Will support Us

Support Us

Coding Ustad LTD Support
Coding Ustad LTD Support

Coding Ustad LTD

Coding Ustad LTD
Coding Ustad LTD

Recent Posts

  • How to Install Node.js and npm on CentOS 7
  • How to Install Node.js and npm on CentOS 7
  • How to Install CentOS Web Panel (CWP) on CentOS 7
  • The Power of Marketing in Real Estate: A Guide to Boost Your Business
  • Vehicle Verification in Pakistan

Get free Hosting

Hostens.com - A home for your website

You may have missed

How to Install Node.js and npm on CentOS 7
4 min read
  • Coding Ustad LTD
  • Education for Everyone

How to Install Node.js and npm on CentOS 7

May 3, 2023
How to Install Node.js and npm on CentOS 7
4 min read
  • Coding Ustad LTD
  • Education for Everyone

How to Install Node.js and npm on CentOS 7

May 2, 2023
How to Install CentOS Web Panel (CWP) on CentOS 7
3 min read
  • Coding Ustad LTD
  • Education for Everyone

How to Install CentOS Web Panel (CWP) on CentOS 7

May 2, 2023
The Power of Marketing in Real Estate: A Guide to Boost Your Business https://thaikadar.com/secureinvestment/
2 min read
  • Article By Spoke Right
  • Blog By Spoke Right
  • Circular Byte Private Limited

The Power of Marketing in Real Estate: A Guide to Boost Your Business

January 30, 2023
  • Home
  • Our Services
  • Free Education
  • Spoke Right News
  • Earn Online
  • Classic Games by Spoke Right
  • Contact Us
Copyright © All rights reserved. | MoreNews by AF themes.