How to Make HTTP Requests in React, Part 2
If you haven’t completed part 1 of this tutorial, do so before starting part 2.
Now that we’ve set up our project using create-react-app, we can start writing some code. Open your project into your editor of choice, and let’s start removing some of the boilerplate that create-react-app adds for you, since we won’t need it.
Step 1: Remove create-react-app boilerplate
When you go into your App.js file, it will look something like this:
Go ahead and delete all of the code from App.js and App.cssand replace it with the code below:
You can also add this code to your App.css file.
You can also delete the logo.svg file, since we won’t be using it. Now, when you run npm start in your terminal, you should see this in your browser:
Step 2: Wire up the handleClick function
Our next step will be set up a function that is triggered when a user clicks the button. We’ll start by adding an onClick event to our button, like this:
When the button is clicked, we will call a function called handleClick that is bound to this. Let’s go ahead and bind handleClick to this . First, we’ll need to create a constructor function in our component. Then, we’ll bind handleClick to this inside of it.
Now, our file should look like this:
Finally, we’ll need to define our handleClick function. Let’s start by making sure that everything is wired up correctly, by having the button console.log ‘Success!’ when the button is clicked.
Here’s what your code should look like now:
You should see this in your browser after clicking the button:
Make sure that when you click the button, you see ‘Success!’ appear in your console. If you do, it means that you’ve correctly wired up your handleChange function to the button, and you’re all set to move on to part 3 of this tutorial.
Do you want design systems tips and tricks sent to your inbox?