Continuation of a series of translations of the section "Advanced Guides" (Advanced Guides) of the official documentation of the React.js library.
In most cases, we recommend using controlled components to implement forms. In the monitored component, the form data is processed by the React component. There is an alternative option - these are uncontrollable components, in which these forms are processed by the DOM itself.
When writing an unsupervised component, instead of writing an event handler for each state update, you can use ref to get the form values from the DOM.
For example, the following code takes the value Name from a form in an unsupervised component:
class NameForm extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { alert('A name was submitted: ' + this.input.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={(input) => this.input = input} /> </label> <input type="submit" value="Submit" /> </form> ); } }
Since in the uncontrolled component the storage of the actual data occurs in the DOM - the use of such components sometimes makes it easier to integrate (combine) React and non-React code. If you are interested in a smaller amount of code (and consequently the speed of its writing) to the detriment of the purity of the code, this is an option. Otherwise, it is better to use controlled components.
In the React lifecycle of rendering (rendering), the value
attribute in form elements will override the value in the DOM. In uncontrolled components, you will often need to set initial values, while leaving subsequent updates uncontrollable. In this case, you can set the defaultValue
attribute instead of value
.
render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input defaultValue="Bob" type="text" ref={(input) => this.input = input} /> </label> <input type="submit" value="Submit" /> </form> ); }
In addition, <input type="checkbox">
and <input type="radio">
support the defaultChecked
attribute, and <select>
supports defaultValue
.
Next part:
Previous parts:
Original Source: React - Advanced Guides - Uncontrolled Components
Source: https://habr.com/ru/post/319520/
All Articles