React uncontrolled components
Created By: chatGPT
Uncontrolled components in React are those that do not store their state in the component but instead rely on the DOM to handle their state. This means that the component doesn't maintain its own state, making it simpler for forms when you do not need to perform validation or other state management tasks in real-time.
class UncontrolledForm extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
handleSubmit = (event) => {
event.preventDefault();
alert('A name was submitted: ' + this.inputRef.current.value);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type='text' ref={this.inputRef} />
</label>
<button type='submit'>Submit</button>
</form>
);
}
}
In this example, we have an
UncontrolledForm
component that uses the ref API to access the DOM element directly. We create a ref using React.createRef()
and attach it to the input element. When the form is submitted, we handle the submission in the handleSubmit
method where we can access the value of the input field via this.inputRef.current.value
.class App extends React.Component {
render() {
return <UncontrolledForm />;
}
}
ReactDOM.render(<App />, document.getElementById('root'));
The ref API allows us to interact with the DOM elements without using controlled components. You won't need to set the state for every keystroke or change in the input. Instead, you can focus on handling the submission and access the value when needed.
<input type='text' ref={this.inputRef} />
This pattern is particularly useful for simple forms where you want to reduce complexity. For instance, it's effective for gathering input for search forms or submitting user input without needing extensive validation on each input change.
handleSubmit = (event) => {
event.preventDefault();
const inputValue = this.inputRef.current.value;
console.log('Submitted value:', inputValue);
};
To recap, uncontrolled components simplify form handling by avoiding state management within React. Instead, they delegate the state to the DOM, which can be beneficial in scenarios where you need less reactivity.
ReactDOM.render(<UncontrolledForm />, document.getElementById('root'));