Developer Diaries — 03

Derek Le
3 min readDec 27, 2021

It’s me.

Lately I’ve been finding myself building a lot of forms in my applications. From coding challenges to my own projects, there’s a <form/>.

So today, I will walk through creating a react form and how to send input information to a server running on your backend.

To get started, let’s set up a skeleton form. We will take in two inputs — a username and password. We will also add a third input to render our submit button.

The next step is to figure out a way to capture information that our users put in. To do that, we will be keeping that in our component’s state. Since this is example is using a functional component, the use of hooks become necessary.

useState gives us access to state functionality similar to class components, and useEffect gives us something akin to lifecycle methods that are also available in class components. To use this in our component, we will need to assign them to a variable. It takes an array that holds a getter and a setter for a state value. We will assign this the value of useState(), which takes an initial state for it’s input.

Now that we have a place to store our user’s input data for further manipulation, the component state, we will need to define how to write to our state. To do this, we will add event handlers to our input and form elements.

For both of our inputs, we added an onChange listener to update our state with the current value of our form. Then, when a user hits submit, the onSubmit handler will capture our current state and send it off to another function that can handle packaging and sending the data off to our server. For this walkthrough, however, we are just going to settle for a console.log() in place of such a function. You’ll also notice the e.preventDefault() function — that prevents the page from refreshing every time our user hits submit.

With this, we now have a basic understanding of how a React form would capture and handle user inputs for us to use elsewhere in the application.

--

--