Form State Management in React
I'm Kuldeep
/@bietkul
What does React Offer?
Controlled Components
Where form data is handled by React Component
Uncontrolled Components
Where form data is handled by the DOM
What's the need of a form library?
-
Form Validation and error Handling
-
Handling form submissions
-
Code Complexity
-
Interaction between input elements
- Performance
Why not redux forms?
"Use React for ephemeral state that doesn’t matter to the app globally and doesn’t mutate in complex ways. For example, a toggle in some UI element, a form input state. Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft."
- Dan Abramov
Problems with the current libraries
-
Dependency issues
-
BoilerPlate
-
UI Independent
-
Nested Forms
-
Dynamic Changes
-
Update Options
React Reactive Forms
-
Zero dependency
-
UI Independent
-
Nested Forms
-
Dynamic Changes
-
Listeners
- Update Options
How it works ?
Create a control
this.myForm = FormBuilder.group({
username: ["", Validators.required],
password: ["", Validators.required]
},
{
updateOn: "submit"
})
<FieldGroup
control={this.myForm}
render={() => (
<form>
<FieldControl
name="username"
render={({ handler, hasError }) => (
<div>
<input type="text" {...handler()}/>
<span>
{hasError("required") && "Please enter username"}
</span>
</div>
)}
/>
<FieldControl
name="password"
render={({ handler, hasError }) => (
<div>
<input type="password" {...handler()}/>
<span>
{hasError("required") && "Please enter password"}
</span>
</div>
)}
/>
</form>
)}
/>
Use the control in React component
<FieldGroup
render={() => (
<form>
<FieldControl
name="username"
render={({ handler, hasError }) => (
<div>
<input type="text" {...handler()}/>
<span>
{hasError("required") && "Please enter username"}
</span>
</div>
)}
/>
<FieldControl
name="password"
render={({ handler, hasError }) => (
<div>
<input type="password" {...handler()}/>
<span>
{hasError("required") && "Please enter password"}
</span>
</div>
)}
/>
</form>
)}
/>
Use Dynamic Controls
componentDidMount() {
this.myForm.get('username').valueChanges.subscribe((value) => {
const passwordControl = this.myForm.get('password')
if(value) {
passwordControl.disable()
// this.myForm.disable()
// passwordControl.setValue("demo")
// passwordControl.setValidators(Validators.required)
// passwordControl.setErrors({ "isExist": true })
}
})
}
Subscribers
React JS Bangalore@31st Form State Management in React
By kuldep saxena
React JS Bangalore@31st Form State Management in React
- 826