React - get input reference

3 points
Created by:

In this article we would like to show you how to get an input element reference in React.

In below example we create a reference using React.useRef hook. Then by an input ref property we attach the input reference to inputRef.

Now to access input DOM element reference we can use inputRef.current property. To get current input value we can use inputRef.current.value.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const inputRef = React.useRef();
  return (
      <input defaultValue="Example text here..." ref={inputRef}></input>
      <button onClick={() => { console.log(inputRef.current); }}>Check reference</button>
      <button onClick={() => { console.log(inputRef.current.value); }}>Check value</button>

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.


React - get input reference
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂