In this two part blog I will be discussing Controlled forms in React. “Controlled form” means that the inputs from the form get their value from our React state. In this first part of this blog series I am going to show you how to set up the start of this app. In the second blog in this series we will connect the React form we are going to build in this blog to a backend in Ruby on Rails. Then we will make all of the necessary adjustments in our React app to communicate with the backend and the database.
So to start off our React frontend we will need to create a React app from our terminal. To do this type in “create-react-app [insert-app-name]” into your terminal. For this example I’ll build a simple pizza app where we can add a type of pizza using our form. Here’s the command for creating a React app.
Now once this command is done creating your app open it in your text editor and go into the src folder and the App.js file. In here we will need to remove some things that we aren’t going to be using. Once you have removed everything that is arbitrary your App.js file should look like so:
You can also remove the className=”App” here if you’d like. Now that this is done we will need to change this from a functional component to a class component. We need this to be a class component so that we can use state. Here are the adjustments required for this as well as the state that we will be using for this first part:
Now, since we aren’t using a backend at the moment we are going to add a couple of things to our pizzas array in state:
Since we aren’t using an actual backend with a database I am just going to put our own id numbers in, keep in mind this is not the same as the id’s that are produced in the backend (if we made another pizza this way we would have to insert the id ourselves). In a database the id’s automatically increment with each new input.