Borislav Hadzhiev
Last updated: Apr 23, 2022
Check out my new book
To get the value of an input field using a ref in React:
ref
prop on the input element.ref.current.value
.import {useRef} from 'react'; const App = () => { const inputRef = useRef(null); function handleClick() { console.log('value 👉️', inputRef.current.value); } return ( <div> <input ref={inputRef} type="text" id="message" name="message" /> <button onClick={handleClick}>Log message</button> </div> ); }; export default App;
The example shows how to get the value of an uncontrolled input field.
Notice that the input doesn't have an onChange
prop or a value
set.
defaultValue
prop. However, this is not necessary and you can omit the prop if you don't want to set an initial value.When using uncontrolled input fields, we access the input using a ref.
The useRef()
hook can be passed an initial value as an argument. The hook
returns a mutable ref object whose .current
property is initialized to the
passed argument.
current
property on the ref object to get access to the input
element on which we set the ref
prop.When we pass a ref prop to an element, e.g. <input ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
useRef
hook creates a plain JavaScript object, but gives you the same ref object on every render. In other words, it's pretty much a memoized object value with a .current
property.It should be noted that when you change the value of the current
property of
the ref, no re-renders are caused.
Every time the user clicks on the button in the example, the value of the uncontrolled input gets logged.
You shouldn't set the value
prop on an uncontrolled input (an input field that
doesn't have an onChange
handler) because that would make the input field
immutable and you wouldn't be able to type in it.