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
.
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const inputRef = React.useRef();
7
return (
8
<div>
9
<input defaultValue="Example text here..." ref={inputRef}></input>
10
<button onClick={() => { console.log(inputRef.current); }}>Check reference</button>
11
<button onClick={() => { console.log(inputRef.current.value); }}>Check value</button>
12
</div>
13
);
14
}
15
16
const root = document.querySelector('#root');
17
ReactDOM.render(<App />, root);