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:
// src/app/Routing.js
...
// Use the following syntax to import the Header
import Header from "../components/header/Header";
function Routing() {
return (
<Router>
{/* Add the Header component as following */}
<Header />
<Switch>
<Route exact path="/" component={HomePage} />
</Switch>
</Router>
);
}
Login Page
In the same way, let's create the Login page in the features/login/ folder:
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:
// Declare a new state variable, which we'll call "username"
const [username, setUsername] = useState('');
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.
// src/features/Login/LoginPage.js
import React, { useState } from 'react';
import { isHatName } from "../../utils/validations";
function LoginPage() {
const [username, setUsername] = useState('');
const [errorMsg, setErrorMsg] = useState('');
const errorMessages = {
usernameNotValid: 'Sorry, this username is not valid'
};
const handleChange = event => {
setUsername(event.target.value);
// Reset the error message when the user is start typing.
setErrorMsg('');
};
const handleSubmit = event => {
event.preventDefault();
validateLoginDetails();
};
const validateLoginDetails = () => {
// Validate the username and display an error message if it's not valid.
if (isHatName(username)) {
// TODO redirect the user to their PDA.
} else {
setErrorMsg(errorMessages.usernameNotValid);
}
};
return (
<form
className={'flex-column-wrapper flex-content-center flex-align-items-center'}
onSubmit={e => handleSubmit(e)}
>
.
.
<input
className={` ${errorMsg ? 'input-error-field' : null}`}
.
.
/>
{errorMsg && <div className={'input-error-label'}>{errorMsg}</div>}
.
.
</form>
);
}