Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The React Workshop

You're reading from   The React Workshop Get started with building web applications using practical tips and examples from React use cases

Arrow left icon
Product type Paperback
Published in Aug 2020
Publisher Packt
ISBN-13 9781838645564
Length 806 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (6):
Arrow left icon
Florian Sloot Florian Sloot
Author Profile Icon Florian Sloot
Florian Sloot
Ryan Yu Ryan Yu
Author Profile Icon Ryan Yu
Ryan Yu
Brandon Richey Brandon Richey
Author Profile Icon Brandon Richey
Brandon Richey
Endre Vegh Endre Vegh
Author Profile Icon Endre Vegh
Endre Vegh
 Theofanis Despoudis Theofanis Despoudis
Author Profile Icon Theofanis Despoudis
Theofanis Despoudis
Anton Punith Anton Punith
Author Profile Icon Anton Punith
Anton Punith
+2 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface
1. Getting Started with React 2. Dealing with React Events FREE CHAPTER 3. Conditional Rendering and for Loops 4. React Lifecycle Methods 5. Class and Function Components 6. State and Props 7. Communication between Components 8. Introduction to Formik 9. Introduction to React Router 10. Advanced Routing Techniques: Special Cases 11. Hooks – Reusability, Readability, and a Different Mental Model 12. State Management with Hooks 13. Composing Hooks to Solve Complex Problems 14. Fetching Data by Making API Requests 15. Promise API and async/await 16. Fetching Data on Initial Render and Refactoring with Hooks 17. Refs in React 18. Practical Use Cases of Refs Appendix

Getting Started – Building Our Baseline Component

To get started with our baseline component, let's think about each of the pieces that we will build and eventually put together to create this form. We are going to build a small component to represent our form and slowly build onto this component to compose it into something more functional.

We will start off with a class-based component since, typically, these interactions will require a certain amount of state manipulation and it's easier if we build the component for that purpose from the start. As discussed in Chapter 1, Getting Started with React, let's go to the Node.js command prompt and start a new Create React App project for this to keep everything separate and easy to follow. We will start off by changing the contents of App.js to just be a simple boilerplate class component. We do this to make it easier for us to iterate on this project and establish a baseline for our UI:

import React, {Component} from 'react';
class App extends Component {
  render() {
    return (
      <div className="App">
        Test App
      </div>
    )
  }
};
export default App;

This should just give us our standard shell App display:

Figure 2.5: Our baseline component

Figure 2.5: Our baseline component

Typically, for components such as these, we also want them to be able to interact with the user in some way, which typically necessitates some form of simple state management. Now, before we can jump into coding the constructor and the basic state representation, we need to first discuss what we are going to build.

To figure out what we will need to include as properties in our state, we will need to take a look at the design and do a little bit of noun extraction to figure out the state of our component.

Note

Noun extraction is the process of exploring the mockup, design, or documentation to find the nouns and use them to inform the general properties or attributes that an object has. It can also be used to identify the objects themselves.

In this case, our form has the following nouns attached to it:

  • Username
  • Password
  • Password confirmation
  • Email
  • A list of errors

We can also make a few assumptions based on the design that will tell us the types for our nouns as well. For example, nearly all of those nouns are strings, with the exception of the list of errors, and even that is just a simple list of strings.

Exercise 2.01: Writing the Starter State for Our Code

Now that we have the general flow designed, we can use that to extrapolate out how the state should be initialized and declared in our constructor. We need to build our initial form and create a scaffold before we can start doing anything more complex, so that will be the objective of this exercise:

  1. Start off your component in src/App.js with the boilerplate code discussed in Chapter 1, Getting Started with React and build a constructor:
    class App extends Component {
      constructor(props) {
        super(props);
      }
    }

    Build out an initial state for your code referencing the design from earlier. Define the state by setting a state property on the object inside of the constructor, and that state needs to be a JavaScript object with each of the appropriate fields in it:

    this.state = {
      username: '',
      password: '',
      passwordConfirmation: '',
      email: '',
      errors: []
    };

    We will also write this into its own function to help us keep our render function nice and lean, so let's write our displayForm() function. It must include the username, password, passwordConfirmation, and email fields that we created in our initial state.

  2. Create a text input for each of those strings and a button to submit the form:

    App.js

    17  <div>
    18    Username: <input type="text" /><br />
    19    Password: <input type="text" /><br />
    20    Password Confirmation: <input type="text" /><br />
    21    Email: <input type="text" /><br />
    22    <br />
    23    <button>Submit</button>
    24  </div>
  3. Next, modify our render function to use this new form:
    render() {
      return (
        <div className="App">
          Create Account
          <hr />
          {this.displayForm()}
        </div>
        )
      }
    }
    export default App;

    When we save and reload from here, we should expect to see the form showing up on our page:

    Figure 2.6: Starter Component

Figure 2.6: Starter Component

This gives us an initial form to work with, built entirely in React and ready to hook into the next functionality we need to start adding: our event handlers.

You have been reading a chapter from
The React Workshop
Published in: Aug 2020
Publisher: Packt
ISBN-13: 9781838645564
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image