3. Main Page & Routing

Main pages and Routing

For this application we'll need 4 routes:

  • "/" for the Home page

  • "/login" for the Login page

  • "/signup" for the Signup page

  • "/authentication" to use it for the authentication callback URL

First, we'll need to install the react-router and react-router-dom dependencies:

npm install react-router react-router-dom

Create a new file Routing.js in the app/ folder and we can include the first Route to the Home page:

// src/app/Routing.js
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import HomePage from "../features/Home/HomePage";

function Routing() {
    return (
        <Router>
            <Switch>
                <Route exact path="/" component={HomePage} />
            </Switch>
        </Router>
    );
}

export default Routing;

Basic components

Home Page

In the feature folder, create a Home/ subfolder in the src/features/ folder with the HomePage.js and HomePage.scss files:

To add a basic navigation for the app, you'll need to create the Header component in the src/components/ folder. Let's create a subfolder header to include the JavaScript and CSS file.

Now, we can import the Header component in the already created Routing.js:

Login Page

In the same way, let's create the Login page in the features/login/ folder:

And include the "/login" Route into the Routing.js:

We can access the Login page on "/login" route or by clicking on the "Login" button.

The HTML form elements work a bit differently from other DOM elements in React. As in HTML, the form element keeps its own internal state, in React we have the option to keep the state in the Component level. For convenience, we can have a JavaScript function to handle the input changes and the submission of the form.

Since React 16.8, we can easily set the state in function components as following:

You can learn more about forms and hooks

Next step is to add the validation for the username. Let's create a validation.js file in the utils/ folder.

The username must follow these rules:

  • start with a letter

  • contain alphanumeric characters only

  • contain lowercase letters only

  • be between 4 and 21 characters

And you'll use this function to validate the user's input and display an error message when the username is not valid to submit. In the LoginPage.js we can validate the user's input and display an error message when the username is not valid to submit. In the onChange method we can reset the error message.

Last updated

Was this helpful?