In React, uncontrolled components are those that do not store their form data in the component state. Instead, they rely on the DOM to manage the form data. Unlike controlled components, which require more integration with React's state management, uncontrolled inputs allow direct access to the form elements and their values using refs.
To change or handle an uncontrolled input in React, follow these steps:
1. Create a Ref
You can create a ref using React.createRef() or the useRef() hook if you are using functional components. This ref will be attached to the input element to access its value.
2. Attach the Ref to the Input
You'll attach the created ref to the input element you wish to manage.
3. Access the Input Value when Needed
You can access the current value of the input directly from the ref when you want to do something with it, usually on form submission.
Example
import React, { useRef } from 'react';
function UncontrolledInputExample() {
const inputRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
alert('A name was submitted: ' + inputRef.current.value);
// You can also manipulate the input value here, if needed.
inputRef.current.value = ''; // Optionally reset the input after submission
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={inputRef} />
</label>
<button type="submit">Submit it</button>
</form>
);
}
export default UncontrolledInputExample;