Form Action

Introducing and using HTML forms rather than HTML input.

Improving our application

We’ll build upon what we have been working on in the last few chapters and add the features of an HTML form element to our app.py file.

To convert our little application into a more conventional HTML form, we have to modify a few lines of code to get the desired results. While the UI hasn’t visibly changed, the behavior reflects the use of the form element.

Using form instead of div

Most of the changes here are in the type of elements we are returning from our React component. Instead of wrapping everything in a plain div element, we change this to a form, passing in a prop containing the onSubmit event value set to call our handleSubmit() function.

el('form',  {'onSubmit': handleSubmit},

We don’t need our “Submit” button anymore because our form will now dictate what action gets taken on submit. However, we do provide an input element that has a prop passed to it that sets type=submit. This ends up getting rendered as a button that has the built-in action of causing the form to be submitted.

el('input',  {'type':  'submit'}),

Prevent default request

Normally when an HTML form gets submitted, it makes a request back to the web server, that returns a response to the web browser, which re-renders the entire page with a possibly updated URL. To get around this behavior, we add a statement to our handleSubmit() function that tells the web browser to not do what it normally does by default:

Get hands-on with 1200+ tech skills courses.