react js-tutorial

React useRef Hook

React 16.8 has a new functionality called the useRef hook. There is a precondition to understanding the ref in react before reading this essay.

UseRef is a hook that enables the functional component to directly construct a reference to the DOM element.

Syntax:

const refContainer = useRef(initialValue);

UseRef produces a ref object that is modifiable. The.current attribute of this object is present. The refContainer.current property retains the value. These values can be obtained through the returning object’s current property. The given input initialValue, such as useRef, could be used to initialise the.current property (initialValue). The component’s whole lifetime can be preserved by the object by storing a value.

Javascript

import React, {Fragment, useRef} from 'react';
function App() {
  // Creating a ref object using useRef hook
  const focusPoint = useRef(null);
  const onClickHandler = () => {
    focusPoint.current.value =
      "The quick brown fox jumps over the lazy dog";
      focusPoint.current.focus();
  };
  return (
    <Fragment>
      <div>
        <button onClick={onClickHandler}>
         ACTION
        </button>
      </div>
      <label>
       Click on the action button to
       focus and populate the text.
      </label><br/>
      <textarea ref={focusPoint} />
    </Fragment>
  );
};
 
export default App;

Output

In this example, there is a button labelled ACTION. When we click on it, the onClickHandler is activated and, with the aid of the useRef hook, it focuses the textarea. The useRef object, which was initially initialised to null and whose value is changing to the onClick event, is the focusPoint. Check out the output of the aforementioned code.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.