1 of 44

React

1

javacream.org

React

2 of 44

please introduce yourself

  • Name
  • Role in the company
  • Subject-related prior knowledge
  • Concrete problem situation
  • Individual objectives

2

javacream.org

React

3 of 44

Initial situation

3

javacream.org

React

4 of 44

client-server programming

4

Web Server

  • Static media server
    • Delivers documents (HTML, CSS, JS, PDF, JPG, ...)
  • Data server
    • RESTful WebServices
      • JSON documents
  • Server-side view
    • Sessions

http/https

Web Browser

  • HTML
  • CSS
  • JavaScript engine
  • Standard plug-ins (JPG, MPG)
  • Custom PlugIns
    • Flash, Java Applets, Silverlight
  • Local Storage
    • SQL database per known / open domain

Take it for granted in the seminar

Relevant for the seminar

javacream.org

React

5 of 44

Evaluation of browser technologies from the perspective of application development

  • HTML
    • Satisfactory
      • Lack of modularization
  • CSS
    • Sufficient
      • Redundancies
  • JavaScript
    • Insufficient
      • No specification
        • ECMAScript or "ES" is completely underspecified
      • Does not fit in with standard developer training
        • Static OOP languages are often taught -> Dynamic, functional
      • Each page change in the browser destroys the existing JavaScript runtime and replaces it with a completely new one

5

javacream.org

React

6 of 44

Solutions to these problems

  • Introduction of a build process that generates a runtime artifact from high-quality languages
    • HTML, CSS and JavaScript are to be regarded as generated
    • Tool: Compiler, more precisely transpiler
  • npm / yarn as a build tool
    • npm registry
      • Frameworks
      • Products (local WebServer, WebPack, Transpiler)

6

javacream.org

React

7 of 44

Evaluation of browser technologies from the perspective of application development

  • HTML
    • Satisfactory
      • Lack of modularization
  • CSS
    • Sufficient
      • Redundancies
  • JavaScript
    • Insufficient
      • No specification
        • ECMAScript or "ES" is completely underspecified
      • Does not fit in with standard developer training
        • Static OOP languages are often taught -> Dynamic, functional
      • Each page change in the browser destroys the existing JavaScript runtime and replaces it with a completely new one

7

npm + WebPack delivers modularization

SCSS is transpiled to CSS

TypeScript / ES is transpiled to JavaScript

javacream.org

React

8 of 44

Solution to the last problem

  • Single Page Application
    • The application does not navigate from the browser's perspective
    • However, implementation requires excessive programming of the browser
    • Frameworks offer ready-made solutions for this
      • React / Angular / Vue
  • State management in the UI
    • Synchronization with the server
      • Asynchronous programming model

8

javacream.org

React

9 of 44

React

  • Framework for single page applications
  • Component model
    • HTML and JavaScript are consistently linked with each other
      • No HTML templates that are linked with JavaScript via a backing object (Angular)
  • Build process based on npm / yarn
  • React tools
    • Project generator
    • Editor support, e.g. through Visual Studio Code Extension
    • Debug support for browsers
  • React itself only has rudimentary state management
    • Reactive Programming (rxjs)
    • Redux with stores

9

javacream.org

React

10 of 44

Choice of programming language

  • JavaScript
    • Better: ES with JSX and React libraries
  • TypeScript
    • A statically typed OOP language with JSX and React libraries
  • C#, Java

10

javacream.org

React

11 of 44

First Contact

11

javacream.org

React

12 of 44

Installation

# installs nvm (Node Version Manager)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash

# download and install Node.js (you may need to restart the terminal)

nvm install 22

# verifies the right Node.js version is in the environment

node -v # should print `v22.12.0`

# verifies the right npm version is in the environment

npm -v # should print `10.9.0`

12

javacream.org

React

13 of 44

A first React project

  • npm create vite@latest training -- --template react
  • cd training
  • npm install
  • npm run dev
  • check
    • localhost:5173 the generated app is displayed in the browser

13

javacream.org

React

14 of 44

Overview of the generated project

  • node_modules
    • Removal of the necessary libraries, tools etc. from the npm registry
      • Completely uninteresting, does not belong in version management, install with npm install
  • package.json (must be in the SCM)
    • Application dependencies, npm scripts, meta information, project configuration
  • package-lock.json (must be in the SCM)
    • Snapshot of the build process performed
  • public
    • web assets
  • src
    • Source code consisting of JavaScript (= ES + JSX) code

14

javacream.org

React

15 of 44

ToDo

  • Creating your own training project
  • Understanding the presentation
    • npm run dev
  • VSC with AutoSave
  • Debugger in Firefox as part of the web developer tools

15

javacream.org

React

16 of 44

Programming model in the App.js

  • Module concept defined in ES
    • import statement makes a module = a JS file visible
      • A relative path specification (./, ../) is relative
      • Otherwise: Reference to the node_modules directory
      • import also works for non-source code files (e.g. images and CSS)
    • export
      • Only exported elements (variables, functions, classes) can be imported
      • There is the default export, which can be imported directly
  • JSX (JavaScript Extensions)
    • Introduction of an HTML literal
    • Caution: An HTML literal may only consist of one top-level element

16

javacream.org

React

17 of 44

React and HTML

  • A React Component is a function that returns an HTML fragment as a result
  • The function is called from another HTML literal
    • <div>...</div> -> React does "nothing" here
    • <CapitalLetter></CapitalLetter> -> React searches for the CapitalLetter() function in the imports, executes it and places the HTML literal in this position

17

javacream.org

React

18 of 44

ToDo: A first user interface

18

App (as before)

PeopleApp (new React Component)

Header ((new React Component))

PEOPLE

Content ((new React Component))

empty

Footer ((new React Component))

Javacream

javacream.org

React

19 of 44

Optional ToDo: A first surface, some design

19

App (as before)

PeopleApp (new React component)

Header ((new React Component))

PEOPLE

Content ((new React Component))

empty

Footer ((new React Component))

Javacream

javacream.org

React

20 of 44

ToDo

  • Introducing the PeopleList in conjunction with the PersonComponent
    • Firstname Lastname
  • Enhancing the personComponent with an additional property: detail
    • if true
      • Add the person's height and gender to Firstname Lastname
    • else
      • Firstname Lastname
  • Optional
    • Use an HTML-Unorderd list to render every Person
      • <ul>
        • <li>entry1</li>
        • <li>entry2</li>
        • <li>entry3</li>
      • </ul>

20

javacream.org

React

21 of 44

ToDo

21

App (as before)

PeopleApp (new React component)

Header (React Component)

PEOPLE

Content (React Component)

  • PeopleList (React Component)

Footer ()

Javacream

model

Person

PeopleModel

  • CRUD

PeopleContext

  • applicationTitle
  • company
  • peopleModel

John Doe

javacream.org

React

22 of 44

UI update in React

22

javacream.org

React

23 of 44

General remark

  • "Decades of UI development in various programming languages have proven that an update function for updating is actually always done wrong by programmers"
  • Modern frameworks hide the details of an update

23

javacream.org

React

24 of 44

React and updating

  • Automatic = algorithm that recognizes when which areas of the UI need to be redrawn based on various triggers
    • Angular uses the Zone-Framework, that knows about various triggers, e.g. Timeout
  • Update APIs in React
    • Component classes with Lifecyle
      • Attribute named "state" will perform an update when changed
      • In modern React demotivated to use
      • Easy to understand
    • Functional approach using Hooks
      • Modern React
      • a kind of magic…

24

javacream.org

React

25 of 44

New component

  • Input for creating personal information

25

State

Load name: <lastname>

javacream.org

React

26 of 44

ToDo

  • Complete the CreatePerson
    • Input fields for ...
    • Submit button or button
    • Click on submit to create a person via the PeopleModel
  • Note
    • The list of people is NOT updated automatically
      • React has a very simple model for updating component hierarchies
      • Correct: Reactive, Redux Store -> later

26

Component

Child component

props

event

javacream.org

React

27 of 44

introduce routing

  • npm install react-router
  • npm install react-router-dom
    • CHECK: package.json

27

javacream.org

React

28 of 44

PeopleList revisited

  • actual:
    • List of People information
  • ToDo
    • "add a delete button for every row, if clicked the person is deleted from the model, no confirmation needed"
    • steps
      • add a method delete_by(id) to PeopleModel
      • add a button to the PersonComponent
      • use onClick to trigger deletion in PeopleModel
    • check: the PeopleList is updated
      • if not: what do we have to do?

28

javacream.org

React

29 of 44

Introduction to the reactive style

29

Data source

subscribe

notification with the changes

Classic observer pattern

Messaging

Event-driven approach

Data source

Pipeline

javacream.org

React

30 of 44

Application design

  • Problem definition
    • "Components should always visualize a current data status"

30

Component 1

Component 2

Component 3

Whiteboard / Blackboard

Subject A

Subject B

Application Model

javacream.org

React

31 of 44

ToDo: In our application

  • Application Model
    • PeopleModel
      • When creating a person, the model will write them with next in a subject on the whiteboard
  • Whiteboard
    • {personCreation: new Subject(), personDeletion: new Subject()}
    • Where to hang the whiteboard -> PeopleContext
  • The person created is stored in a subject with next()
  • Subscriptions
    • PeopleList
      • Caution: Lifecycle!
    • Optional: CreatePerson the representation of a created person
  • Introduction of a log component
    • This shows the last 3 actions performed
  • Introducing a DeletePerson

31

javacream.org

React

32 of 44

Very popular implementation of Reactive

  • RXJS
  • Data sources
    • Subjects

32

javacream.org

React

33 of 44

Navigation

33

javacream.org

React

34 of 44

Page navigation in React is optional(?)

  • There are React-associated frameworks
    • Server-side React
    • React Native
  • Installation via npm
    • npm install react-router react-router-dom

34

javacream.org

React

35 of 44

ToDo

  • Introduction of the navigation according to the presentation / current GitHub
  • Please collect the link elements in a separate navigationComponent
  • Introduce a "Welcome page" that you can navigate to with "/"
    • "the great people application"

35

javacream.org

React

36 of 44

Redux

36

javacream.org

React

37 of 44

Motivation

  • "Actually, what we have achieved so far is not so bad after all"
    • Open point
      • The components are still relatively smart
        • You call up the model functions directly
  • "Redux First Contact -> non-transparent, overhead..."
    • Redux Developer Toolkit as a browser extension

37

javacream.org

React

38 of 44

Application design

  • Implementation of the flux pattern (general) using the "Redux" framework

38

Component 1

Component 2

Component 3

Store

State A

State B

Reducer functions

(oldState, payload)=>newState=...

Action Builder

  • Creates action objects
  • Action: Name string + payload

Dispatcher

Name of the action identifies the reducer to be called

javacream.org

React

39 of 44

History

  • Use of Redux in React applications
  • Originally
    • There is an implementation for the store
    • The store is created by specifying a set of reducer functions
    • The store offers a dispatch function
    • Store offers a subscribe function
    • React-Redux-Bridge
      • Connecting the components to the store
        • Quite verbose, lots of boilerplate
        • https://github.com/Javacream/org.javacream.training.react/tree/16.9.2021/redux_sample

39

javacream.org

React

40 of 44

Current status

  • Even more opaque
    • Full utilization of the potential of a dynamically untyped language
  • Tool: "@redux/toolkit"
    • This tool is not a static code generator, but generates the following at runtime
    • npm install @reduxjs/toolkit
    • Actions and reducers must now be written

40

+

-

Meter reading: 42

javacream.org

React

41 of 44

Asynchronous programming

41

javacream.org

React

42 of 44

Several possibilities

  • Sync call
    • Pseudocode Synchronous
      • let response = fetch(url)
      • let result = response.json()
  • Solution
    • Callback functions
      • fetch(url,(response) => {response.json((result) => ...) })
    • Promise API
      • let responsePromise = fetch(url)
      • responsePromise.then((response) => response.json()).then((result)=>...)
    • Reactive
      • fetch(url).subscribe((result) => ...)
    • async await
      • let response = await fetch(url)
      • let result = await response.json()

42

not so: that would be a blocking action!

javacream.org

React

43 of 44

React and TypeScript

43

javacream.org

React

44 of 44

React and Typescript

  • npm create @vire/latest training_ts -- ---template react-ts
  • https://github.com/Javacream/org.javacream.training.react/tree/16.9.2021/training-ts

44

javacream.org

React