ECE366 - Lesson 6

Intro to Javascript and React

Instructor: Professor Hong

Review & Questions

## Basic HTML
## What is HTML? - HyperText Markup Language (not a programming language) - Standard markup language for website creation - Maintained World Wide Web Consortium (W3C) - Parts - opening tag, content, closing tag
## New pom.xml Dependency - Building upon last week's JPA example ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` - Thymeleaf templates allow you to create basic web applications
## Web Controller web/PlayerController.java ``` package com.ece366.rpsjpa.web; import com.ece366.rpsjpa.business.PlayerService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/players") public class PlayerController { private final PlayerService playerService; public PlayerController(PlayerService userService) { this.playerService = userService; } @GetMapping("/getAllPlayers") public String getPlayers(Model model){ model.addAttribute("players", this.playerService.getPlayers()); return "rps-players"; } } ```
## Webservice API webservice/WebserviceController ```java import com.ece366.rpsjpa.business.PlayerService; import com.ece366.rpsjpa.data.Player; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api") public class WebserviceController { private final PlayerService playerService; public WebserviceController(PlayerService playerService) { this.playerService = playerService; } @GetMapping("/testPlayer") public String getTestPlayer() { return "TEST PLAYER"; } @GetMapping("/players") public List<Player> getPlayers(){ System.out.println("getPlayers"); return this.playerService.getPlayers(); } } ``` Add `@RequestMapping("/api")` annotation
## Index.html resources/static/index.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RPS</title> </head> <body> <h1>Welcome to RPS</h1> <p><a href="/players/getAllPlayers">Players</a></p> </body> </html> ```
## rps-users.html resources/templates/rps-users.html ``` <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>RPS: Players</title> </head> <body> <h1>RPS Players</h1> <table> <tr> <td>Player ID</td> <td>Player Name</td> <td>Password</td> <td>Total Wins</td> </tr> <tr th:each="player: ${players}"> <td th:text="${player.playerId}">PlayerId</td> <td th:text="${player.userName}">UserName</td> <td th:text="${player.password}">Password</td> <td th:text="${player.totalGames}">TotalGames</td> </tr> </table> </body> </html> ```
## Running the Site ``` localhost:8080 localhost:8080/players/getAllPlayers localhost:8080/api/players ``` You can read more here: [https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html](https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html)
## Deleting a Player - rps-players.html ``` <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>RPS: Players</title> </head> <body> <h1>RPS Players</h1> <table> <tr> <td>Player ID</td> <td>Player Name</td> <td>Password</td> <td>Total Wins</td> <th>Actions</th> </tr> <tr th:each="player: ${players}"> <td th:text="${player.playerId}">PlayerId</td> <td th:text="${player.userName}">UserName</td> <td th:text="${player.password}">Password</td> <td th:text="${player.totalGames}">TotalGames</td> <td> <form th:action="@{/players/delete/{id}(id=${player.playerId})}" method="post"> <button type="submit">Delete</button> </form> </td> </tr> ```
## web/PlayerController ``` @PostMapping("/delete/{id}") public String deletePlayer(@PathVariable Long id) { playerService.deletePlayerById(id); return "redirect:/getAllPlayers"; } ```
## Intro to React
## What is React? - Javascript library - Created at Facebook - Open-sourced in 2013 - Docs: [https://react.dev/reference/react](https://react.dev/reference/react)
## What is Javascript? - High level, interpreted language - Allows you to implement complex features on web pages - Used with HTML and CSS (for styling) - Logging: ```console.log();```
## Setup/Installation - Add React Developer Tools from Chrome Extensions and add to chrome - Inspect Element -> Components - Can also install on Firefox
## React in Index.html ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin ></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin ></script> <!-- Production Build <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script> --> <title>React ⚛️</title> </head> <body> <h1>Getting Started with React</h1> </body> </html> ```
## React in Index.html ``` <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <title>React ⚛️</title> </head> <body> <div id="root"></div> <script type="text/javascript"> const root = ReactDOM.createRoot(document.getElementById("root")); root.render( React.createElement("h1", null, "Getting Started!") ); </script> </body> </html> ```
## ReactDOM.createRoot ReactDOM.createRoot() - 1 argument - a DOM element that will serve as the root container for the React application
## Variable Names ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <title>React ⚛️</title> </head> <body> <div id="root"></div> <script type="text/javascript"> const root = ReactDOM.createRoot(document.getElementById("root")); const heading = React.createElement( "h1", { style: { color: "blue" } }, "Heyyyy Everyone!" ); root.render(heading); </script> </body> </html> ```
## JSX, Babel ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script> <title>React ⚛️</title> </head> <body> <div id="root"></div> <script type="text/babel"> const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <ul> <li>🤖</li> <li>🤠</li> <li>🌝</li> </ul> ); </script> </body> </html> ``` - Babel - a JS compiler to use next-generation JS - Javascript XML - Can access variables with ```{``` variable ```}```
## More JSX syntax ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script> <title>React ⚛️</title> </head> <body> <div id="root"></div> <script type="text/babel"> let robot = "🤖"; let cowboy = "🤠"; let moon = "🌝"; let name = "React"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <ul> <li>{robot}</li> <li>{cowboy}</li> <li>{moon}</li> <li>{name.toUpperCase()}</li> <li>{name.length}</li> </ul> ); </script> </body> </html> ```
## React Components - A function that returns JSX and can be rendered in DOM - Should use capital letter for component/function name - Multiple React components should be wrapped into 1 component - Can be used to display dynamic data
## Component Properties - Add props argument to component functions - A container where you can put any properties in the component
## Example with React Components and Image ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script> <title>RPS</title> </head> <body> <div id="root"></div> <script type="text/babel"> function Header(props) { return ( <header> <h1>{props.name}'s RPS</h1> </header> ); } function Main(props) { return ( <section> <img height={200} src="./rps.png" alt="Rock Paper Scissors" /> <ul> {props.users.map((user) => ( <li key={user.id}> {user.title} </li> ))} </ul> </section> ); } function Footer(props) { return ( <footer> <p>Copyright {props.year}</p> </footer> ); } const users = [ "Alpha", "Beta", "Gamma", ]; const userObjects = users.map( (user, i) => ({ id: i, title: user }) ); function App() { return ( <React.Fragment> <Header name="Cooperps" /> <Main adjective="amazing" users={userObjects} /> <Footer year={new Date().getFullYear()} /> </React.Fragment> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<App />); </script> </body> </html> ```
## React
## Create React App - Install nodejs - [https://nodejs.org/](https://nodejs.org/) - nodejs on WSL - [https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl) - Remove old version of node: ``` sudo apt-get purge --auto-remove nodejs ``` - ```node -v``` - to check node version - ```npm -v``` - check npm version - ```npx create-react-app rps``` - ```npm start```
## Important Parts - package.json - dependencies - react, react-dom, react-scripts - src/index.js - entry point of the application, main JS file - renders App - React.StrictMode - additional checks - public/index.html - similar to index.html w/ all your JSX injected ``` npm install npm start ```
## Javascript Destructuring Allows you to get specific elements from an argument/props ``` function App({ myVariable }) { return ( <div className="App"> <h1>{myVariable}</h1> </div> ); } ``` - Also Array destructuring allows you to get certain elements from an array
## Changing States with useState App.js ``` import "./App.css"; import { useState } from "react"; function App() { const [emotion, setEmotion] = useState("happy"); return ( <div className="App"> <h1>Current emotion is {emotion}</h1> <button onClick={() => setEmotion("sad")}> Sad </button> <button onClick={() => setEmotion("excited")} > Excited </button> </div> ); } export default App; ```
## Side Effects with useEffect ``` import "./App.css"; import { useState, useEffect } from "react"; function App() { const [emotion, setEmotion] = useState("happy"); const [secondary, setSecondary] = useState("tired"); useEffect(() => { console.log(`It's ${emotion} around here!`); }, [emotion]); useEffect(() => { console.log(`It's ${secondary} around here!`); }, [secondary]); return ( <div className="App"> <h1>Current emotion is {emotion}</h1> <button onClick={() => setEmotion("sad")}> Sad </button> <button onClick={() => setEmotion("excited")} > Excited </button> <h2> Current secondary emotion is {secondary}. </h2> <button onClick={() => setSecondary("grateful")} > Grateful </button> </div> ); } export default App; ``` - dependencyArray is the 2nd argument for useEffect - No argument makes it called everytime - Empty array makes it called once
## Fetching Data from Service fetch is built into the browser to make an HTTP request to get data ``` import "./App.css"; import { useState, useEffect } from "react"; function App() { const [data, setData] = useState(null); useEffect(() => { fetch( `http://localhost:8080/api/players` ) .then((response) => response.json()) .then(setData); }, []); if (data) return ( <pre>{JSON.stringify(data, null, 2)}</pre> ); return <h1>Data</h1>; } export default App; ```
## Update CORS in Spring Boot server WebserviceController.java ``` @CrossOrigin @GetMapping("/players") ``` Can also put it after @RestController above the class definition