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.

Example: 

  • Input.js
import React from "react"

const Input = React.forwardRef((props, ref) => {
    const {value, placeHolder, onclick} = props;
    return(
     <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 = ()=>{
    inputRef.current.focus();
  }
  return (
    <div className="FormBox">
      <h3>Ref Forwarding</h3>
      <Input ref={inputRef} value={'Hello'}  />
      <button onClick={()=>handleOnClick()}>Click Here</button>
    </div>
  );
}

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.

OUTPUT:-

Submit a Comment

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

Subscribe

Select Categories