How to Use ForwardRef in React
React js with forwardRef function provides parent components “forward” (move down) refs to their child components. When a parent component of a React component is referenced by a child component using the ForwardRef function, then A DOM entity is generated. The child can read and modify elements automatically using a script.
Syntax
The following syntax shows the React js with the forwardRef function.
- React.forwardRef((props, ref) => {})
- It accepts a function in props with ref arguments as parameters.
- Return Value: A JSX Element is the result of this function.
React Application Development
The following steps are used to develop a react application.
Step 1:
Use the command to create a React.Js Development:
- npx create-react-app folder_name
Step 2:
The following command is used to move your project folder. It works after creating a folder with a name such as folder_name.
- cd folder_name
How to Implement ForwardRef?
In React, parent components utilise props to provide data to their children. Consider creating a child component with additional accessories to change the actions.
- We need to modify the behaviour of a child component without the state or redraw the component.
- We can accomplish the behaviour of the child component using refs. Elements represent the DOM nodes. It can be accessed using references of the nodes.
- We can change it without impacting its current state or re-rendering it.
- The parent component has to provide a method for the child to obtain the ref. The child component must connect to the current node of its parent node. The Ref forwarding is the method’s name for the react.js implementation procedure.
Examples
The following examples show the forwardRef of the React.Js.
Example 1:
The following example is used to get the working procedure of the forward. The input tag with the focus button shows on the web page. The focus function works for the input field if we click the button.
- import * as React from “react”;
- import ReactDOM from “react-dom”;
- export default function App() {
- const ref_var = React.useRef();
- function focus() {
- ref_var.current.focus();
- }
- return (
- <div className = “App”>
- <input ref = { ref_var} placeholder = “write input data” />
- <button className = “button” onClick = {focus}> Focus </button>
- </div>
- );
- }
- const rootElement_var = document.getElementById(“root”);
- ReactDOM.render(<App />, rootElement_var);
Output:
The form elements and their operation are shown as output.
Example 2:
If we click the button without data, the function does not work for the forwardRef.
- import { useState } from “react”;
- import reactLogo from “./assets/react.svg”;
- import viteLogo from “/vite.svg”;
- import “./App.css”;
- import * as React from “react”;
- import ReactDOM from “react-dom”;
- export default function App() {
- const ref_var = React.useRef();
- function focus() {
- ref_var.current.focus();
- alert(“Please fill data in input field”);
- }
- return (
- <div className = “App”>
- <input ref = { ref_var} placeholder = “write input data” required/>
- <button className = “button” onClick = {focus}> Submit </button>
- </div>
- );
- }
- const rootElement_var = document.getElementById(“root”);
- ReactDOM.render(<App />, rootElement_var);
Output:
The form elements and their operation are shown as output.
How Significant is ForwardRef?
The following list shows how important forwardRef is in React JS.
- The forwardRef is significant to enable more adaptable and effective component composition in React.
- There are multiple times operations with complicated applications. The parent component needs direct access to a child component of the DOM element or instance.
- The multiple-time functionalities work due to React’s default behaviour. It is possible when working with higher-order or wrapper components (HOCs).
- We can send an identifier from a parent component to the child component using forwardRef. It works after the child component is contained within another component.
- It provides direct communication between the parent component and the DOM element or object of the child.
Example
The following code shows the default use of the forwardRef in React JS. When we click the button, counter count and increment by 1.
- import React from ‘react’
- class App extends React.Component {
- constructor(props) {
- super(props)
- this.aRef = React.createRef()
- }
- render() {
- return (
- <>
- <counter ref={this.aRef} />
- <button onClick={() => { console.log(this.aRef) }}>
- Ref
- </button>
- </>
- )
- }
- }
- const Counter_info = React.forwardRef((props, ref) => {
- class Counter_info extends React.Component {
- constructor(props) {
- super(props)
- this.state = {
- count: 0
- }
- }
- render() {
- return (
- <div>
- Count of Value: {this.state.count}
- <button ref={ref} onClick={() => this.setState(
- { count: this.state.count + 1 })}>
- Increment
- </button>
- </div>
- )
- }
- }
- return < Counter_info />
- })
- export default App
Output:
The counter with a button shows as an output.
Explanation
- The value of the ref attribute on the button element is set in the ref parameter, such as a Counter component.
- The App component renders the Counter component.
- First, the ref is created.
- The ref attribute of the Counter component is given the value aRef.
- The HTMLButtonElement of the button in the Counter component is stored in aRef.
- The Ref button’s click will confirm the functional count with Ref and the HTML button element object used as the button.
- The Counter component is transmitted to the child component, and the increment is per button click.
Forwarding refs in React using ForwardRef
The parent component needs to transmit the ref to the child when the child component needs to reference the current node of its parent component. Referencing is the term for the method of the forwardRef.
A ref is automatically passed via a component to one of its children using the ref forwarding approach. It is most required to create reusable component libraries. It helps to pass the ref to a child component and utilise the forwardRef function.
The component uses the FancyButton to obtain a ref to the underlying button DOM node and utilise it as required.
Here is a step-by-step breakdown of what transpires in the example above:
- By invoking React, we produce a React ref.Make a ref variable as a recipient of createRef.
- We declare our ref as a JSX attribute and pass it to the fancy button as a ref.
- React gives the ref as a second argument to the “(props, ref)” method inside forwardRef.
- By designating this ref parameter as a JSX attribute, we pass it down to the <button ref={ref}>
- When the ref is attached, the ref.current draws attention to the DOM node as a “button.”
Example
The given example works with the button click and input data. When you click the given button, an alert message shows on the alert box.
- import { useState } from “react”;
- import reactLogo from “./assets/react.svg”;
- import viteLogo from “/vite.svg”;
- import “./App.css”;
- import * as React from “react”;
- import ReactDOM from “react-dom”;
- const InputText = React.forwardRef((props, ref) => (
- <input ref={ref} {…props} />
- ));
- export default function App() {
- const ref = React.useRef();
- function focus() {
- ref.current.focus();
- alert(“work properly”);
- }
- return (
- <div className=“App”>
- <InputText ref={ref} placeholder = “my input” />
- <button className = “button” onClick = {focus}>Focus</button>
- </div>
- );
- }
- const rootElement = document.getElementById(“root”);
- ReactDOM.render(<App />, rootElement);
Output:
The counter with a button shows as an output.
Using References Improperly in React
The ref’s feature enables direct interaction between developers and DOM elements and components. There are several circumstances where there may be better action than using references. To name a few:
- Misuse of DOM manipulation
React promotes a declarative approach to UI development. It is essential to steer clear of using references for direct DOM manipulation. Most UI modifications can be handled using component state and props.
- stateless component overuse of refs
Functional parts are frequently designed to become straightforward and stateless. Consider splitting a functional component into smaller ones. You frequently use multiple references or move state management to a higher-level component. The stateless component is used multiple times.
- data flow references
Refs must refrain from utilising in place of prop passing or state management. State management tools like Redux or React’s Context API are used, but component props should be the primary channel for data flow.
- replacing controlled components with references
Use controlled components in form elements whenever possible (by setting the value and managing input changes using state and event handlers). When there is a specific necessity for easy access to the DOM element, references should only be utilised for uncontrolled components.
- accessing the internal state of child components
Using references to access a child component’s internal state or methods is not recommended. Instead, connect between parent and child components using callbacks or additional state management methods.
Conclusion
Refs are an effective tool in React that enables instant access to DOM nodes, opening up many methods and possibilities for creating cleaner, more feature-rich, and more performant components.