React Js hooks

Hooks introduced in 16.8 in react js. 

 

1)forwardRef : This hook is used to forward the DOM reference , created inside the parent component to the child component.

a)Create the ref in parent component App.js

import React from “react”;
import Child1 from ‘./Child1’;
const  App = ()=> {
  let inRef = React.useRef(null);
  return (
    <div>
      <h1>Example for forwardRef</h1>
      <Child1 ref={inRef}>Check It</Child1>
    </div>
  );
}

export default App;

b)Pass the ref created in parent component to the child component

import React from “react”;
const  Child1 = React.forwardRef((props , ref) =>{
  const applyFocus = ()=>{
    ref.current.focus();
  }
  return (
    <div>
    <input ref={ref}/>
     <button onClick={applyFocus}>Click</button>
    </div>
  );
})

export default Child1;

Attach the ref to the input.

Site Footer