Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

sENG365 LAB 4

srRucruR1Nc CL1ENr.s1DE APPL1cAr1oNs 1N REAcr

SENG365

17th February 2023

Purpose of this Lab

In last week’s lab we looked at using React to create client-side application. In this lab we build on the technologies we applied last time with a focus on structuring our application for maintainability, scalability, and readability.

1 Exercise 1: Initial Setup (Same as Lab 3)

We are again building a front-end application for the chat app API we wrote in Lab 2. For this we will need to run the chat app API as discussed Lab 3, if there any issues please refer back to that Lab.

2 Structuring Large Applications with React

In this lab, we will rewrite the client-side chat application built in last week’s lab. The diference being that this week, we will look at structuring our application beter, making use of TypeScript, and looking at some other helpful libraries.

2.1 Single Page Applications (SPAs)

Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app.

SPAs use AJAX and HTML5 to create fluid and responsive Web apps, without constant page reloads. However, this means much of the work happens on the client side, in JavaScript. 1

3 Exercise 2: Planning

This exercise is going to run through how to implement the‘User’functionality. The first thing you should do before developing an application is to plan how it will look and how a user will interact with the functionality (and the routes that will hold each page). For the User functionality, let’s look at how a user will interact with the application in Figure 1.

Figure 1: User functionality plan.

We start at the applications home page. The user clicks the‘Users’link to navigate to /users. The /users page includes a list of all users, each with a link to view that specific user (located at /users/id). When viewing an individual user, there is the option to ’Edit’or ’Delete’that user. Editing the user opens a modal with a form to edit the user. If the delete buton is clicked, another modal is displayed asking the user to confirm the action. If the user closes the delete modal, they are taken back to /users/id. If they confirm the delete operation, then the specified user is deleted and they are sent back to /users.

Note: A modal2 is a pop-up that appears on top of content and provides extra information or the ability to complete some extra action.

1.  Plan out the rest of the application, this can just be a rough sketch for now and may change when you get to implementation. However, sketching the application structure out before coding will allow you to get an idea of the ’bigger picture’before you start implementing which can help avoid making small oversights that lead to refactoring later down the line.

4 Exercise 3: create-react-app

create-react-app3is a tool that helps you create React projects easily. create-react-app allows for a degree of custom- isation with the use of templates (in our case TypeScript). create-react-app creates a workflow using webpack4, which among other features allows us to run code on a development server with one command (with real-time updating as we change the code).

1. Create a directory lab4 and navigate to it in the terminal.

2.  Install create - react -app using npm5with the following command: npminstallcreate - react -app

3.  Run the command:

npxcreate - react -appchat -app --templatetypescript

Note: This may take a few minutes

4.  In your lab4 directory, a new chat-app directory should have been created. This contains the skeleton for our project. Have a look around and get familiar with the new structure.

(a)  Inside chat-app/src we have the index.html file along with App.tsx6 (which replaces our old app.js from our previous lab)

5. There are a few things we can remove to make our application a litle cleaner, though this is not a requirement. (a)  Remove the App.text.tsx and setupTests.ts files within the src folder (within the scope of this course we

do not expect you to test front-end code).

(b) Within index.tsx in your src folder remove the React .StrictMode HTML tags and the reportWebV i tals() method call and import statement. Finally delete the reportWebVitals.ts file.

(c) You can also remove the node_modules folder and package.json files (along with any others) generated at the root of your lab4 directory as these were only needed for running the create-react-app command.

6. Create a .env file in your chat-app directory. Within this add the line:

This specifies the port to use when running the application (if you have something running on this port simply choose another one e.g., 8081)

7.  Navigate to the chat-app directory in your terminal and run:

npmrunstart

A new tab should open in your browser with the default React page similar to the image below (if it does not

automatically open click the link in the terminal, or navigate to localhost:8080 in your browser manually).

5 Exercise 4: Routing with react-router-dom

Now that we have our project set up, we need to define a client-side router so that we can create our desired structure. A client-side router works similarly to the server-side express router we used in earlier labs and assignment 1, matching URLs to specific elements.

To implement routing in React we will use the third party routing library ’react-router-dom’7.

1.  In the terminal, navigate to your chat-app directory.

2.  Run the command:

npminstall --savereact - router -dom

Note: the --save will save the module to our dependencies in the package.json file.

3.  In App.tsx replace the default code with the following from Listing 1.

1 import React from 'react ' ;

2 import ' ./App .css';

3 import {BrowserRouter  as  Router,  Routes,  Route} from "react-router-dom" ;

4 import Users from " ./components/Users";

5 import User from " ./components/User";

6 import NotFound from " ./components/NotFound";

7

8 function App()  {

9 return (

10               


11                    

12


13                                

14                                     }/>

15                                     }/>

16                                     }/>

17                               

18


19                    

20


21          );

22    }

23

24 export default App;

Listing 1: App .tsx content

4. Now we need to create three diferent elements we will use for our routes, From the code we can see these are User, Users, Not Found all within the components directory. Within the src directory create the components directory.

5. Create a new .tsx file for each of User, Users, and Not Found; within them add the code from Listing2(swapping Not Found for User and Users to match each file).

1 const NotFound =  ()  => {

2 return (<h1>Not Foundh1>)

3 }

4

5 export default NotFound;

Listing 2: Component boilerplate content

Note: Commonly tsx file are placed in either a components or pages directory. With the distinction being a page is ofen tied to a route and is composed of many components, with components being the tsx that encapsulates smaller functionality. Within the scope of this lab we do not need to worry about this distinction, however when working on your assignment doing so may help you keep everything organised.

6. Finally, we need to create our type definition file and add the User type that we will use throughout the lab. Create a folder types within the src directory and create a new file users .d .ts with the type definition from Listing 3.

1 type User = {

2 /**

3 * User id as defined by the database

4 */

5 user_id : number,

6 /**

7 * Users username as entered when created

8 */

9 username : string

10 }

Listing 3: User type

6 Exercise 5: Adding the Functionality

6.1 Exercise 5.1: Listing all Users

1.  In your terminal install axios8with the command:

npminstall --saveax ios

Then import it into your Users.tsx file.

1 import axios from 'axios ' ;

Listing 4: ax ios import

2. Within the users.tsx add the following state and function declarations. Also notice that we have introduced the React .useEffect hook, in this case it simply fetches all users when the page loads, we discuss hooks more in Section 6.2 below when dealing with a single user.

1 const [users , setUsers]  = React .useState < Array < User >>  ([])

2 const [errorFlag, setErrorFlag]  = React .useState(false)

3 const [errorMessage, setErrorMessage]  = React .useState( "")

4 React .useEffect(()  =>  {

5 getUsers()

6 },  [])

7 const getUsers =  ()  =>  {

8 axios .get('http://localhost:3000/api/users')

9 .then((response)  =>  {

10 setErrorFlag(false)

11 setErrorMessage( "")

12 setUsers(response .data)

13 },  (error )  =>  {

14 setErrorFlag(true)

15 setErrorMessage(error .toString())

16 })

17 }

Listing 5: Users state and function declaration