JS-201-ReactFundamentals
  • Part 0: App Overview
  • Part 1: Intro to React
    • 1.0: Packages Setup
    • 1.1: Project Setup
    • 1.2: React Router Dom
  • Part 2: JavaScript Concepts
    • 2.0: ES6 Overview
    • 2.1: classes
    • 2.2: constructors
    • 2.3: extends
    • 2.4: super
    • 2.5: interpolation
    • 2.6: map
    • 2.7: filter
  • Part 3: Functional Components
    • 3.0: Functional Components Overview
    • 3.1: Calling Functional Components
    • 3.2: Single Element Rule
    • 3.3: Arrow Functions
    • 3.4: Challenge
    • 3.4: Solution
    • 3.5: Challenge 2
    • 3.5: Solution 2
  • Part 4: JSX Challenge
    • 4.1: JSX Overview
    • 4.1: Challenge Answer
    • 4.2: className
  • Part 5: Class Concepts
    • 5.1: State
    • 5.2: setState
    • 5.3: Class Components Challenge
    • 5.4: Class Components Challenge Answer
  • Part 6: Props Starter
    • 6.0: Props Overview
    • 6.1: Props Demo and Challenge 1
    • 6.2: Props Answer 2
    • 6.3: Props Passing Functions and Challenge 2
    • 6.4: Props Answer 2
    • 6.5: External Props and Mapping Components
    • 6.6: PropTypes
  • Part 7: Lifecycle Methods
    • 7.0: Lifecycle Overview
    • 7.1: Lifecycle Methods
    • 7.2: Mounting Methods
    • 7.3: Update Methods
    • 7.4: Unmount Methods
  • Part 8: Apps
    • 1.0 - Small Timer Apps
      • 1.1 - Simple Timer
      • 1.2 - Clock App
      • 1.3 - Stop Watch App
      • 1.4 - Challenge
    • 2.0 - Concept List
      • 2.1 - Concept Data
      • 2.2 - Concept App Component
      • 2.3 - Concept Component
      • 2.4 - Concept List Component
    • 3.0 - NYT
      • 3.1 - NytApp Component
      • 3.2 - Nyt Results
    • 4.0 - The Friend List App
      • 4.1 - Friend List App Component
      • 4.2 - Friend Component
    • 5.0 - Movie Search Application
      • 5.1 - Form Component
      • 5.2 - Form Results Component
      • 5.3 - Styled Components
    • 6.0 - YouTube Api
      • 6.1 - Video Component
      • 6.2 - Video Component
      • 6.3 - Video Component
    • 7.0 - Github Api Application
      • 7.1 - The Users
      • 7.2 - Github API Component
      • 7.3 - Github API Card
      • 7.4 - Github API Card Form
      • 7.5 - Github API Card List
      • 7.6 - Github API Search
      • 7.7 - Github API Challenge
    • 8.0 - Bitcoin Api Application
      • 8.1 - Bitcoin API Setup
      • 8.2 - Bitcoin API Fetch
      • 8.3 - Bitcoin API Line Chart
      • 8.4 - Bitcoin API Fetching Data
      • 8.5 - Bitcoin API Info Box
      • 8.6 - Bitcoin API Completed Code
    • 9.0 - Google Maps Api Challenge
    • 10.0 - Sound Cloud App Challenge
    • 11.0 - VR App Challenge
    • 12.0 - React Native Intro
  • Part 9: Project
  • Part 10: Notes
    • 10.1 - Resources
    • 10.2 - Troubleshooting
Powered by GitBook
On this page
  • imports and API_Base
  • Friend List App Form
  • Add the routes
  • Constructor and friends array
  • Add a handleSubmit method
  • Call onSubmit()
  • Fetch
  • The Final Code
  1. Part 8: Apps
  2. 4.0 - The Friend List App

4.1 - Friend List App Component

This app will be highly useful in illustrating how to pass data from a form using React. Chances are, you'll have to do it. You'll notice some patterns from previous applications, just different syntax.

imports and API_Base

Set up a few imports and a class component. See the code below. We encourage you to type everything except for the API_BASE.

import React, { Component } from 'react';

const API_BASE = "http://rest.learncode.academy/api/efa/friends";

class FriendListApp extends Component {
    render() {
        return (
            <div className="main">
                <div className="mainDiv">
                    Placeholder for an input form.
                </div>
            </div>
        );
    }
}

export default FriendListApp;

Just like in plain JavaScript files, we're keeping our API_BASE capitalized because it is convention to put caps on constants, and this is a base that will be a constant.

Friend List App Form

Let's create a Friend List App form now inside of the render and inside of our two container divs. Note that we put some extra space for clarity:

class FriendListApp extends Component {
    render() {
        return (
            <div className="main">
                <div className="mainDiv">


                ***********    Start the form ***********
                  <form>
                    <h3>Enter a Friend!</h3>
                    <fieldset className="form-group">
                      <label>Friend's Name:</label>
                      <input
                        type="text"
                        ref="name"
                        name="name"
                        className="form-control"
                      />
                    </fieldset>

                    <fieldset className="form-group">
                      <label>Friend's Age:</label>
                      <input
                        type="text"
                        ref="age"
                        name="age"
                        className="form-control"
                      />
                    </fieldset>
                    <button className="btn btn-success" type="submit">
                      Save Friend
                    </button>
                  </form>
                ***********    Finish the form ***********
                </div>
            </div>
        );
    }
}

export default FriendListApp;

Add the routes

We need to get our routes set up.

  1. Just so you can practice and get stronger, we'll leave it up to you to go to Sidebar.js and do this. We are calling our route 'friendlist'. Don't forget that examples of adding a route are available in Part 1, section 1.4.

  2. When you fire up the app, and go to that route, you should get a form with two input fields and a button. Again, you should see something like this form in this app at this point (styling may be different, you can always style later):

Of course, if you press submit, there is no data being passed. We are going to need a method for that.

Constructor and friends array

We are going to need an array for our collection of friends. Just like in the past, we are going to set the state of the array in our constructor, before anything renders:

class FriendListApp extends Component {

    ************ Add ***********
    constructor(props) {
        super(props);
        this.state = { friends: [] }
        console.log('Constructor',this.state.friends)
    }
    ************ Finish Add ***********

We pass in props, as we've discussed in the past, and we set the initial state to having a blank array called friends. Remember that you can console log the state by console.log(this.state.friends) right before the closing curly brace. You should see the empty array in Chrome:

Add a handleSubmit method

A good way to wire up a button with a method is to first simply log something when you press the button. We'll now add a handleSubmit() method. Eventually, this will take care of our http post. First, we need to set up some variables inside the method:

    constructor(props) {
        super(props);
        this.state = { friends: [] }
    }

    ********** add ***********
    handleSubmit = event => {
        event.preventDefault();
        console.log("Button pressed.");
        var name = this.refs.name.value;
        var age = this.refs.age.value;
        console.log("Name:", name);
        console.log("Age:", age);

        var friendsTemp = this.state.friends;
        console.log(friendsTemp);
    }

        ********** add ***********

It's important to note that handleSubmit is not a React method. It's not a life cycle method or any other built in method in the React API.

It's just a convention that is used by React developers to call something that is handling some event with the word 'handle' as the starting word in the method signature.

Call onSubmit()

Nothing is happening yet though. We need to connect the button to the method. Let's call this function in the form. We can call it in the the onSubmit of the form:

    render() {
        return (
            <div className="main">
                <div className="mainDiv">
                        *********** Call handleSubmit ***************

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

                        *********** Addition done *******************
                                <h3>Enter a Friend!</h3>

Now, when we press the button, our console.log in the handleSubmit method should fire off. You should see this:

Fetch

So we now have the button hooked up and we need to pass that data off to our API. To do that we'll use fetch to make a post request to the api url. For clarity, we went ahead and tore out the console.log methods in the handleSubmit method. You can keep them, if you'd like. Under the newly created variables let's add the following post request:

    handleSubmit = event => {
    event.preventDefault();
    var name = this.refs.name.value;
    var age = this.refs.age.value;
    var friendsTemp = this.state.friends;
******* START ADD *******
    fetch(API_BASE, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name, age })
    })
      .then(res => res.json())
      .then(response => {
        friendsTemp.push(response.data)
        this.setState({ friends: friendsTemp })
        this.refs.name.value = ""
        this.refs.age.value = ""
        console.log(response)
      })
******** END ADD **********
  }

You should get the response data back in the console. Woohoo!

Notice also that the form clears when we hit submit. That's because we used refs again, where we set this.refs.name.value="". As we get the response from the server, we set the input fields to blank strings. This is handy to know!

The Final Code

In the next module we'll create the actual Friend component. Here is the final code for this section:

import React, { Component } from "react";

const API_BASE = "http://rest.learncode.academy/api/efa/friends";

class FriendListApp extends Component {
  constructor(props) {
    super(props);
    this.state = { friends: [] };
  }

  handleSubmit = event => {
    event.preventDefault();
    var name = this.refs.name.value;
    var age = this.refs.age.value;
    var friendsTemp = this.state.friends;

    fetch(API_BASE, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name, age })
    })
      .then(res => res.json())
      .then(response => {
        friendsTemp.push(response.data)
        this.setState({ friends: friendsTemp })
        this.refs.name.value = ""
        this.refs.age.value = ""
        console.log(response)
      })
  }

  render() {
    return (
      <div className="main">
        <div className="mainDiv">
          <form onSubmit={this.handleSubmit.bind(this)}>
            <h3>Enter a Friend!</h3>
            <fieldset className="form-group">
              <label>Friend's Name:</label>
              <input
                type="text"
                ref="name"
                name="name"
                className="form-control"
              />
            </fieldset>

            <fieldset className="form-group">
              <label>Friend's Age:</label>
              <input
                type="text"
                ref="age"
                name="age"
                className="form-control"
              />
            </fieldset>
            <button className="btn btn-success" type="submit">
              Save Friend
            </button>
          </form>
        </div>
      </div>
    );
  }
}

export default FriendListApp;
Previous4.0 - The Friend List AppNext4.2 - Friend Component

Last updated 7 years ago

Blank Form
State
Console Button
axios-response