How To Use ForwardRefs In React

Forwarding Refs

  • Forwarding Refs means to forward the ref (reference) to the child components.
  • It can be used when the component is reusable

When we can use Refs

  • Refs can be used when we need to trigger some action, selection, focus some element or increment/decrement and many more such operations.


  • Input.js
import React from "react"

const Input = React.forwardRef((props, ref) => {
    const {value, placeHolder, onclick} = props;
     <input ref={ref} className="inputBox" value={value}  placeholder={placeHolder} onClick={onclick} />

export default Input
  • App.js
import Input from './pages/Input';
import { createRef } from 'react';
import './App.css';

function App() {
  const inputRef = createRef();

  const handleOnClick = ()=>{
  return (
    <div className="FormBox">
      <h3>Ref Forwarding</h3>
      <Input ref={inputRef} value={'Hello'}  />
      <button onClick={()=>handleOnClick()}>Click Here</button>

export default App;

Here we have passed the ref to the input component which can be further used in different components wherever required. We have used the ref to focus the input when user clicks on the button.


Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories