Journey, React

Creating a form with React

Let’s create a simple form where all it does is take the submission and displays it.

Yes it sounds simple but there is a lot going on where it can get confusing. But once you get the basics down then everything else that has to do with a form is just an extension of this.

Let’s get started by creating a new react app, cleaning out the template code so we are left with just a blank page.

Next let’s create the form component

Things to remember when creating a component

  • Always import react
  • Your class should have  a render function and a return function.
  • Everything inside the return function should be inside a div or section or something or it will cause an error.
  • Don’t forget to export the class.

With just a simple h1 our form component looks like this.

We have our simple shell. Before we do any more coding let’s think this out and make steps to follow.

  1. The user will fill in the text field.
  2. The user will hit submit and the text will be displayed on the page
  3. The text field will clear itself out and the user can do this again.

This part was simple enough as this is what the user sees but there is more happening on the back end and this is what we have to code in.

  1. We need an array that will hold our data : STATE to create
  2. The data in the array needs to be displayed on a separate line : PROPS to pass down
  3. Add the form with 1 input field and 1 button
  4. Capture the text input value: STATE
  5. Change the value of state with an event listener.
  6. Add the new item to the array
  7. Clear the input field
  8. Bonus: Don’t allow an empty field to be passed in.

This might seem like a lot but in reality it’s not because we broke down our problem into such small steps that we can get each one done in a few minutes.

The thing about coding is that the biggest challenge isn’t the coding it is knowing what to code and if you spend the time before hand to break down the problem, now we just have to worry about the syntax of the language.

Create an array

I am using an array in this example but in the real world outside of learning we would be using a database. 

This array is to be modified therefor it should be inside of the state, let’s create the state with our array inside. Remember that our state has to be inside a constructor that uses props. The other thing is that state expects an object so our array has to be inside of an object. It will look like this. Notice how I used some dummy text and that is just to make sure that we have some data to work with on the next step. 

Display data in array

In React, it’s very common to see items iterated through an array with the .map() method, so we will use that here to display each item from our array. Our method is going to look like this:

{ this.state.formItems.map( (element, index) =>
     <Form key={ index } />
)}

In React each list item needs to have an individual key attribute so we use the index of the array. This way we know that each item has an individual key value.

Somehow we need to get the array information from the app file to our form element and we use props for this. Just as a reminder props are made to be passed down from a parent element (app in this case) to it’s child components (form). We are passing down the items in the array. We are just going to add this to the information in our

<Form key={index} formElement={element} />

Now in our form element we can access those props with the this.props object and we can render each item in our Form component

Add the form

The form itself is no different than any other form you have ever created.

<form>

   <input type=“text” />

   <input type=“submit” />

</form>

The  app can go below the text we are displaying so that the user can read through the list before submitting a new item.

Capture the text input value

This is where al the complications happen!

warning

We have to put what the user has typed into a variable so that in the next step we can push it into the array.

We don’t want anything to happen until the user hits the submit button. Lucky for us there is onSubmit attribute that we can add to the form tag. the value will be an arrow function.

<form onSubmit={ (e) => this.handleSubmit(e) }>

In this example e is short for event, but it could be anything you want to name it, it is just common practice to use the letter e.

We are calling the handleSubmit(e) function but it doesn’t exist yet so on top of the file below the component(props) we can create our function.

We are going to call preventDefault to prevent the page from reloading when the submit button is pressed.

handleSubmit(e) {
   e.preventDefault();
}

If you wanted to test it to see if it’s actually working we could add a console.log() and check the console.

We don’t need our dummy text in our  array so we can delete it leave it blank.  After our array we can create a variable to hold the user’s input.

The last change you will see is that we set the value of the text element into our variable.

Add an event listener

If you run the app now and enter a word nothing is going to happen. All that work for nothing, well we are putting the information in our variable but we need to change the value in state so that it renders on the screen.

There is an event listener that listens for changes called onChange we will then use it to call a new function titles handleChange.

Just like before the handleChange function doesn’t exist so we will create it. This new function will set the state of newFormElement to whatever was stored in the value field.

Add the new item to the array

Now we just have to add the new item to the array. You would think that it would be as easy as to use the push method. But react doesn’t want us to change state directly as errors can happen.

We will use our handleSubmit function to add the new item.

handleSubmit(e) {
    e.preventDefault();
    this.setState({formItems: […this.state.formItems, this.state.newFormElement] });
}

It’s almost like if we created a new array that contains the previous elements plus the new one.

Clear the input field

It is not clearing the input field after the item is passed to the array. This is a quick fis that can be accomplished by changing the state of the newFormElement varible by assigning it to ‘ ‘.

handleSubmit(e) {
    e.preventDefault();
    this.setState({formItems: […this.state.formItems, this.state.newFormElement], newFormElement: ” });
}

Bonus: Don’t allow an empty field to be passed in.

Before we add the item to the array we can check to see if it’s empty and if it is then we exit the function by using the keyword return.

And that is all that there is to it. With just these steps it is possible to add new items to the form and output them to the page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s