Middle
How do you access an uncontrolled input and its value in React?
sobes.tech AI
Answer from AI
In React, a ref is used to access an uncontrolled input and its value. An uncontrolled component is one where the value is not stored in React state but is managed by the DOM itself.
Example:
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
alert(inputRef.current.value); // get the current value of the input
};
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Show Value</button>
</>
);
}
Here, inputRef.current refers to the DOM element input, and through the .value property, you can get the current value of the field.