React form submission tutorial

How to Submit Forms and Save Data with React.js and Node.js

In my last two tutorials, I covered the basics of React.js and form error handling in React.js. In each case, I used hard-coded data. React is a front-end library, providing no easy way to save to, or read information from, a database or file. That is the part we will cover in this tutorial.

React is a user interface library, so it is common to use a different library or framework to do all the back-end work. One of the most common pairings is React.js with Node.js. Lucky for us, we already have a tutorial on the basics of Node right here on HTML5 Hive!

The main React Facebook tutorial does something similar to what we will be doing with this tutorial, and they also provide a Node server, as well as many other server examples within their download files. Although our Node server will be similar, our front-end React interface will have a few extra complications. In fact, I’ll be using the same files from my form error handling React tutorial, with a few updates that will allow the saving and reading of information from a file or database.

Download the tutorial files

You can download all the files used in this tutorial from here.

Learn React online

If you are keen to learn React from the ground-up feel free to check Learn and Understand React JS on Zenva Academy which covers all the basics + lots of bonus topics like React Router and Flux.

Tutorial requirements

  • You must have basic knowledge of React.js and JavaScript. For a beginner’s guide to React, please see my past tutorial. In addition, I will be using many of the same functions from my other React tutorial, so you may want to read that one as well.
  • You will need to use the React library, although we will be using CDN links to get around that during testing.
  • You will need to download a text editor of some sort. You can use just a plain text editor, although Notepad++ is popular on Windows, and TextMate is popular on Mac machines. An editor with code highlighting capability is preferable.
  • You will need to read and follow the directions in most of the beginner’s Node.js tutorial in order to create the server that will be used later in this tutorial.

Making revisions to a React user interface

I will be using the same files I created for the error handling tutorial, with some simple revisions that will make it possible to read and save data. The files with all the revisions are provided above. The index file from the previous tutorial remains the same, but now we are going to be pulling data from a file, then posting new form entries to the file.

The original file was set up with some of the code needed to post and read data, but some parts were commented out, since we had no server to do the work. All we have to do is uncomment those lines, and we have this:

So far, everything we have here is similar to Facebook’s Commenting tutorial. We save all the data from the file in a DonationBox component state, then set an interval to pull new donations from the server so the user can see new donations as they come in, in close to real time. On each form submission, the data is pushed to the database (or in this case, the file). We include JQuery in the index file in order to make the loading and submitting of data easier.

Let’s continue with the changes I’ve made to the form before discussing the server side.

Displaying new data from everyone

We now have a new listing that will display all new donations coming from all users.

Similar to the Facebook tutorial, we are mapping out all the data from the JSON file into a new Donation component for each entry. We then display the entire donationNodes list. Let’s take a look at the new Donation component:

This is actually simpler than what we see in the Facebook tutorial, because we are expecting comments by contributors to be in plain text. We are simply displaying the main donation information, leaving out anything private. In fact, we are only saving the public information for the purposes of this tutorial, but it’s easy enough to store all of the data in a database, then only display the information that is public.

So far, our additions are very similar to what you can find in the Facebook tutorial, but our original Donation app is nothing like that tutorial. This is where the changes become a little more complicated.

Submitting form data

In the original donation app, we had some fairly complicated calls to other components that allowed us to serve up multiple fields from a single component. Now that we have to think about actually saving and displaying that data, we have to add a value attribute to the components that will allow us to empty all the fields after submission, and we also have to save all the data in a state.

As you can see, we’ve added new states for each piece of data we plan on saving. The other bits of data can always be added later, but we are just going to focus on the data that we want to display. On submit, we send all the data to the parent component to do the actual saving to the server. We then reset all the fields so they will appear empty after submission.

We also have a new method called setValue. Because we do not have form fields directly within this component, we have to have a way to set the state as we go (using the onChange attribute in each component call). Rather than create a new function for every form field, we use this single function by taking the field as a variable, and using it to create a new object that can be used to set the state for that field. The field name is included in the call to the component.

Each component call also has a new value attribute. This is what allows us to empty all the fields when the form is submitted. I’ve have also added a new text field, with an option for producing a textarea rather than a single line text field. This allows us to add a new comment field for contributors who want to say something about why they’re donating. Now let’s take a look at the few changes made to the form element components.

Emptying fields on form submission

There are no changes to the InputError component, but we do have a few small changes to the other components which will allow us to empty all the fields after submission.

The TextInput component has the simplest change because all we have to do is set the value to the props value sent to the component. We were already calling this.props.onChange from the handleChange function for real-time error processing, and simply rearranged the error processing a bit in the parent component so we can save the data. We still call the parent validation method when the user leaves the field.

We do add one additional input field to handle the textarea option. When the text field is a textarea, we have to use the textarea field. Otherwise, it’s a normal text field. There are no other changes.

The only changes made to the Radios component have to do with the addition of the value attribute. You may have noticed that the default and reset values sent to the Radios and Department components are “undefined.” That’s because there’s always a possibility that one of the radio or select options could be 0 or an empty string, but both components also contain an “any value” text field. The only way to truly unset these radio and select fields, therefore, is to set the value to undefined.

Properly setting the regular radio buttons is easy. We just select the radio button using the selected attribute if it matches the value, as we iterate through each radio button:

Just because we are using the value property to empty the fields doesn’t mean that we don’t have to set the current value. Remember that we are saving the state as the user makes changes, but that state change causes the display to update, which means that we have to set the value correctly even when the field is not empty. Otherwise, the fields would be set to empty as soon as a user makes a change!

We then put the “undefined” setting to use when deciding whether to select the “other” option:

If the value is undefined, then we know not to select anything, because we are emptying all the fields. If it’s not undefined, however, and the value does not match any of the other radio buttons, then we know we have a custom value.

For the optional text field, we just need to set the value if it exists:

There are no changes to the Payment component, but we do have a small change to the Department component (even though we aren’t actually saving the value):

Since this is a select field with an “any value” text field, we have to check for “undefined” again:

The Department component is a little bit different from the others, in that the options are simply hard-coded. The only reason it’s a separate component is to simplify the code in the DonationForm component. As such, the easiest way to set the correct value is to simply check against the hard-coded values. This is similar to what we did in the Radios component, but with hard-coded values. We then set the text field based on whether they’ve selected “other.”

Saving data to the server

Now we get to save the data and watch the changes happen! Our example hinges on the installation of Node.js. Most of what needs to be done is covered in the beginner’s Node.js tutorial. If you follow all the directions in that tutorial, within the folder for your project, you’ll wind up with a package.json file. The only addition to that tutorial is to install body-parser along with express. After installing express, you will need to run the same command, but with body-parser:

This will give you a package.json file similar to the one included with the files for this tutorial:

We use server.js for our example, since we are creating a server, although the file in the Node.js tutorial is called script.js. You can use either name as long as the name in your package file matches the name of your Node file.

From there, you would create your Node server in whatever way you see fit. The server can do additional processing and error checking, and should include security measures as well. It can also save information to a database, and read from a database. In our example file, we simply save to, and read from, a file called donations.json. In fact, our server is so simple that it’s very similar to Facebook’s server.js file, included within their tutorial files. You can’t really make it more simple than that!

If using the files with this tutorial, all you have to do is install Node.js (which includes npm), then go to the same folder as the package.json file and run the following command on the command line:

Once it’s installed, just run the following command:

But look at the following line in package.json:

This means that you can also start the server by running the following command:

The server will then start, and tell you right where you need to go in your browser: http://localhost:3000/

Once you open that URL, you should see a list of donations, with the ability to add new donations. In addition, if you add a field directly to the donations.json file, it will display on the screen almost immediately!

Screen Shot 2015-11-17 at 8.03.00 PM

Comments and Questions?

Please let me know if you have any questions or suggestions in the comments section below. I welcome your input!

Published by

Kristen Dyrr

Kristen is a software engineer, tinkerer, podcaster, writer, web developer, and business owner. She has written both entertainment pieces for Yahoo TV and tech pieces for Yahoo Tech. She has her own blog containing gif-tweet-recaps for various TV shows, incorporating animated gifs and humorous fan tweets. She also hosts Red Shirted: The 100 Podcast and Baker Street Podcast for Southgate Media Group. She will also have a small speaking role in the movie Shallow Water, but only if it funds on Kickstarter!

Share this article