This is part of the Ext JS to React blog series. You can review the code from this article on the Ext JS to React Git repo.
In the preceding blog posts, we looked at how to create various form fields in React as well as how to validate user input. In this article, we’ll look at how to take the user input and send it off to a remote server for processing. In Ext JS, the Form panel handles the submission of form data for you using its built-in submit method. The form collects up all of the values in the form and posts the form data to your remote server. The controller logic to handle the submission is pretty straightforward: Get the form >> form.submit()
.
Note: While not a requirement for React, this article’s code examples assume you’re starting with a starter app generated by create-react-app.
Ext JS Form and View Controller
Before we get to the React form example, let’s first recap the approach taken in Ext JS:
Ext.define('MyApp.view.FormController', { extend: 'Ext.app.ViewController', alias: 'controller.formcontroller', onSubmit: function() { var form = this.getView(); form.submit({ url: 'url/to/submit/to', success: function() { Ext.Msg.alert('Form submitted successfully!'); } }); } }); Ext.create({ xtype: 'form', renderTo: Ext.getBody(), controller: 'formcontroller', items: [{ xtype: 'textfield', fieldLabel: 'Full Name' }], buttons: [{ text: 'Submit', handler: 'onSubmit' }] });
React Form Example
Fortunately for us, we’ve been defining our form fields as controlled components. That means that we’re cataloging user input within the component’s state object and that in turn feeds each form field’s value. This makes fetching the form’s data set quite simple. In the following example, we’ll illustrate a simple form and how we can submit the data to a remote server. We’ll skip custom validation and CSS layouts for the sake of keeping the example tidy:
import React, { Component } from 'react'; class App extends Component { state = { username: '', password: '' } handleSubmit = (e) => { e.preventDefault(); // fetch('https://yourserver.url/submit-json', { // method: 'post', // body: JSON.stringify(this.state) // }).then(response => response.json()).then(console.log); // Fake a submit. We just setTimeout() and return a fake result setTimeout(() => { alert('login successful'); }, 1000) } handleChange = (e) => { const { target: { name, value }} = e; this.setState({ [name]: value }); } render () { const { password, username } = this.state; return ( <form onSubmit={this.handleSubmit}> <input type="text" value={username.value} name="username" placeholder="username..." onChange={this.handleChange} required /> <br /> <input type="password" value={password.value} name="password" placeholder="password..." onChange={this.handleChange} required /> <br /> <input type="submit" value="Submit" /> </form> ); } } export default App;
React Form Class Explained
Let’s take a closer look at this example by first looking at what each method is doing:
handleSubmit
- Prevent the default browser submit action since we’ll handle the form data ourselves
- Use the fetch API to send the form data to a remote server
- The
body
of the fetch request is our form component’s state object serialized - Fetch returns a promise that we can use to evaluate the remote server’s response
- The
handleChange
- Store the input field’s name and value as variables
- Set the state using the input field’s name / value as the state key / value pair
render
- Get a reference to our
state
for use in the returned JSX - Return the form markup
- The
<form>
element with itsonSubmit
action linked to the component’sonSubmit
method. This enables the form to be submitted using the submit button or hitting[enter]
with a form field focused - A text field, password field, and a submit button (with
required
set as an attribute on the input fields, we’ll let the HTML form do any validation checks for itself on submit)
- The
Wrap Up
Creating your own custom form and form field components gives you the ultimate flexibility in form layout, validation, and submission handling. However, you may opt for a pre-built solution to handle user input while you labor over other (quite possibly more interesting) aspects of your web application. As mentioned in the previous article on form validation, there are two popular React form packages worth looking into: react-form and Formik. These pre-built solutions handle form validation, custom inputs, nested forms, and form submission for you and are certainly worth a critical review as you continue to develop your React mastery.
In the example in this article we implemented the form submission only. The next steps would be to implement field validation and disable the form fields and mask the form along with a waiting indicator while the form is sent off to the server. Check out some of the other blog articles in the Ext JS to React series and implement the remaining application logic for pure fun!
Mitchell Simoens
Related Posts
-
Ext JS to React: Form Validations
This is part of the Ext JS to React blog series. You can review the…
-
Ext JS to React: Migration to Open Source
Worried about Migrating from Ext JS? Modus has the Answers Idera’s acquisition of Sencha has…