Handle Form Submissions In React to a MongoDB backend

This is the second post in creating the frontend of a clocking in app on React. This post will show you how to add new data (staff member) to the already set up local backend in MongoDB. We’ll be using hooks to store and update our states.

Yousef Ahmed
Create a Clocking in System in React
2 min readMay 29, 2020

--

1. Create a Form in a New Component

Our first step will be creating a basic form for us to take the user’s input. Since our backend is so simple, our form will only take one input of ‘name’ (the rest of the fields will be set to default values).

2. Make our State & Update Function

The form we’ve created above is just eye candy at the moment, and serves no functionality. So let’s start adding some; firstly we have need to temporarily store the name when the input field is changed. We can use states for that:

However we need to link the input field to update the state, or it will eternally stay undefined. With an update function, we can monitor any changes to the input field and have it update the state accordingly:

Now if we smush it all together, the name monitoring component should look like this:

Remember to include the function in the input tag (line 16), as well as importing useState() in the first line.

3. Post your Data

Now that we know our state is linked to the form’s input field, we can proceed with submitting this new data. Our next step is creating a function that will handle our form once it’s been submitted.

(If your backend isn’t set up yet, you can revisit the other post on setting up a local MongoDB database)

Once we’ve written the handler, we add it to our form tag. If we smush it all together we get this completed component:

4. Testing Time!

The moment of truth:

Voila! Our app is successfully able to post data to the backend 🙌🏼

--

--