Related Articles

Related Articles

React JS useRef Hook
  • Last Updated : 27 Oct, 2020

The useRef hook is the new addition in React 16.8. Before proceeding to this article there is prequisite to know about the ref in react.
The useRef is a hook that allows to directly create a reference to the DOM element in the functional component. 

Syntax:

const refContainer = useRef(initialValue);

The useRef returns a mutable ref object. This object has a property called .current. The value is persisted in the refContainer.current property. These values are accessed from the current property of the returned object. The .current property could be initialised to the passed argument initialValue e.g. useRef(initialValue). The object can persist a value for a full lifetime of the component. 

Example: How to access the DOM using useRef hook.

Javascript



filter_none

edit
close

play_arrow

link
brightness_4
code

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;

chevron_right


Output: In this example, we have a button called ACTION, whenever we click on the button the onClickHandler is getting triggered and it’s focusing the textarea with help of useRef hook. The focusPoint is the useRef object which is initialised to null and the value is changing to onClick event. Let’s see the output of the above code.

react-js-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :