EN
React - get input reference
3
points
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 (
<div>
<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>
</div>
);
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);