1 of 46

7 - Intro to React.

Speck Academy 2021

2 of 46

Basics

JSX

Components

Props

SCSS (Sass)

Basic routing

1

2

3

4

5

6

Overview

3 of 46

1

Basics

4 of 46

Basics overview

About React

Development environment

Create a React App

File structure

Import and export

5 of 46

About React

React is a JavaScript library for building user interfaces maintained by Facebook.

With React you can:

  • Design simple views for each state in your application
  • Update and render just the right components when your data changes
  • Build encapsulated components that manage their own state, then compose them to make a complex UIs

Some of the key terms to understand:

  • Single-page Application (SPA)
  • Virtual DOM

6 of 46

About React

Single-page Application is an application that loads a single HTML page and all the necessary assets (such as JS and CSS) required for the application to run.

  • Any interactions with the page or subsequent pages do not require request to a server
  • Building a single-page app in react is not a requirement

Virtual DOM is a programming concept where an representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM.

  • This approach enables the declarative API: You tell React what state you want the UI to be in, and it makes sure the DOM matches that state
  • Virtual DOM is usually associated with React elements since they are the objects representing the user interface

7 of 46

Development environment

Development environment for React Apps consists of the following technologies:

  • Node.js - an open-source JS runtime environment for easily building server-side applications. It’s also the runtime that powers many client-side development tools for modern JS frameworks (React, Vue, Angular...).
  • npm (Node Package Manager) - stands for two things, first and foremost, it is an online repository for the publishing of open-source Node.js projects. Second, it is a command-line utility for interacting with said repository that aids in package installation, version management, and dependency management.

A plethora of Node.js libraries and applications are published on npm, and many more are added every day.

8 of 46

Development environment

npm comes bundled with Node.js, so there is no need to separate installation.

How to use npm?

  • Browse npm packages on npmjs.com
  • Install package by running command in terminal: npm install <package-name>
  • Uninstall package by running command in terminal: npm uninstall <package-name>
  • Update package by running command in terminal: npm update <package-name>
  • When you have a node project with package.json file, you can run terminal command from the root of the project to install all of the dependencies: npm install

9 of 46

Development environment

How npm works?

  • npm by itself doesn’t run any package. If you want to run a package using NPM, you must specify that package in your package.json or specify local path to that package.

When executables are installed via npm packages, npm creates links to them:

  • Locally: npm install <package-name> (links created in /node_modules/.bin/)
  • Globally: npm install -g <package-name> (links in global directory, /usr/local/bin/ on Linux & Mac, %AppData%/npm on Windows).

To conclude, if you are using npm, each package must be installed, then you can run it if it’s available in package.json or in global PATH variable.

10 of 46

Development environment

Sometimes you’ll use npx instead of npm, so don’t be confused with it:

  • npx is also CLI tool whose purpose is to make it easy to install and manage dependencies hosted in the npm registry.
  • It allows us to run any sort of Node.js based executable that you would normally install via npm.
  • npx always runs latest version, there is no need to have globally installed package.
  • It can execute a locally installed package, as an packages that are not previously installed.
  • Find more on npx web, stackoverflow discussion and in blog post.

Working with Node.js, npm, and npx can be tedious at times, so be patient and research the errors on the Internet and try to find the solution that works for you.

11 of 46

Development environment

package.json vs package-lock.json

  • package.json - information to npm that allows it to identify the project as well as handle the project dependencies. When entry is added to that file, npm supports some wildcards in the semver definition. By default, npm installs the latest version, and prepends a caret e.g. “^3.3.0”. This signifies that at minimum, version 3.3.0 should be used (any higher version is also ok).
  • Problem with package.json occurs when you are sharing project, and from time to time some dependency version changes on the npm repo. Then two developers will probably have two different versions of dependency in the same app.
  • In order to solve this problem, we are using package-lock.json.

12 of 46

Development environment

package.json vs package-lock.json

  • package-lock.json - it is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
  • If you want to install new dependencies, or to update existing dependencies, and do the modifications in both, package.json and package-lock.json, use the: npm install
  • If you want to install dependencies without modifying the package-lock.json, where exact version of package will not be changed, use the: npm ci
  • Find more: package.json, package-lock-json, npm install, npm ci

13 of 46

Create a React App

In order to create React App you’ll need to have development environment which consists of Node >= 8.10 and npm >= 5.6.

To create a project, run the following commands:

  • npx create-react-app my-app
  • cd my-app
  • npm start

create-react-app doesn’t handle backend logic or databases, it just creates a frontend build pipeline, so you can use it with any backend you want.

14 of 46

File structure

/node_modules - all of the installed dependencies

/public - root folder served by the server

  • index.html - script files (react app) will be injected here

/src - source files and folders of App

  • App.js - root component of App
  • App.css - styles for root component
  • index.js - renders App
  • index.css - “global” styles

package.json - list of all dependencies

15 of 46

File structure

/node_modules - all of the installed dependencies

/public - root folder served by the server

  • index.html - script files (react app) will be injected here

/src - source files and folders of App

  • App.js - root component of App
  • App.css - styles for root component
  • index.js - renders App
  • index.css - “global” styles

package.json - list of all dependencies

Additional folders, we can group folders for pages , components and assets on this way (not required).

16 of 46

File structure

React doesn’t have opinions on how to put files into folders.

There are a few common approaches popular in the ecosystem:

  • Grouping by features or routes - locate CSS, JS and tests together inside folders grouped by feature or route
  • Grouping by file type - group similar files together

Grouping by features or routes

Grouping by file type

17 of 46

Import and export

React applications are basically a collection of interactive components.

If we want to create fully-fledged React app created of collection of components, we first need to know the way to use and reuse components that may have been defined elsewhere.

Inside React app usually we will import user-defined components or modules installed with npm.

When we are importing user-defined components we are using relative path to file. In case of importing npm module, then name of module is enough.

18 of 46

Import and export

Read more about import and export.

Importing default export

Importing named values

Library installed inside node_modules

Importing style, this runs module (css,scss...)

Relative path to file

Exporting default export

19 of 46

2

JSX

20 of 46

JSX

JSX stands for JavaScript XML.

JSX allows us to write HTML elements in JavaScript and place them in the DOM without a createElement() method.

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function.

JSX is converted into JS with Babel.

21 of 46

JSX

  • We can define variable and use it inside JSX
  • Any valid JS expression inside curly braces can be inside JSX
  • JSX is an expression
  • Use camelcase naming convention for JSX
  • If a tag is empty, you may close it immediately with “/>”
  • HTML class attribute must be className attribute in JSX (React has reserved class word for classes)
  • Multiple elements must be wrapped by root <div></div> or <></> inside return statement inside component

22 of 46

JSX

JSX prevents injection attacks.

By default React DOM escapes any values embedded in JSX before rendering them.

You can never inject anything that’s not explicitly written in your application.

Everything is converted to a string before being rendered.

This helps prevent XSS (cross-site-scripting) attacks.

23 of 46

3

Components

24 of 46

Components

About components

Class components and State & Lifecycle

Functional components and Hooks

25 of 46

About components

Component let you split the UI into independent, reusable pieces, and think about each piece in isolation.

Conceptually, components are like JS functions.

They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

React component can be:

  • Class
  • Functional

26 of 46

Class component

Must use class keyword and inherit Component.

Class based component can have state and lifecycle methods.

Implement constructor if you need to initialize state and/or bind methods. The constructor for a React component is called before it is mounted.

When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor.

27 of 46

Class component

You should not call setState() in the constructor, use local state instead. Constructor is the only place where you should assign this.state directly.

In all other methods, you need to use this.setState() instead.

Method setState() merges the object you provide within setState() into the current state object you are working with. In other words only properties inside setState() will be changed inside state object.

Avoid copying props into state!

28 of 46

Class component

Method componentDidMount() is invoked immediately after a component is mounted (inserted into the tree).

Initialization that requires DOM nodes should go here, or if you need to load data from sa remote endpoint, this is a good place to instantiate the network request.

Method componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method.

29 of 46

Class component

Method render() is the only required method in class component. When called, it should examine this.props and this.state and return one of the following types:

  • React elements, Arrays and fragments, Portals, String and numbers, Booleans or null

The render() function should be pure, meaning that it doesn’t modify component state, it returns same result each time it’s invoked.

Find more about React.Component state & lifecycle.

30 of 46

Functional component

Functional components are used in most cases.

Hooks are introduced in 16.8 version of React and they provide us similar behaviour such as State and Lifecycle methods in class components.

Almost any task can be implemented by use of Functional components.

useState() hook is used to setup initial state of functional component.

useEffect() hook is used instead componentDidMount() in class component.

31 of 46

Functional component

There is no equal hook to lifecycle method componentWillUnmount(), but we can use return inside useEffect() and empty array as an second argument to achieve same behaviour.

Also, useEffect() hook and lifecycle method componentDidMount() are not equal.

Hook useEffect() fires after layout and paint, in most cases this is not the problem.

If you are converting class component to functional component, try to use useEffect() first.

32 of 46

Functional component

If useEffect() causes problem, then use useLayoutEffect(), it fires in the same time as and componentDidMount() and componentDidUpdate().

33 of 46

4

Props

34 of 46

Props

Special keyword in React, which stands for properties and is being used for passing data from one component to another (parent to child component).

  • Props data is read-only, and the name of the props attribute is defined by the user (use camelCase names).
  • There are some default props, and an important one is props.children which accepts everything that is passed inside tags of the component.
  • Each children component has access to props and all of the props attributes defined to that child component inside the parent component.

35 of 46

5

SCSS (Sass)

36 of 46

SCSS (Sass)

Sass is a stylesheet language that’s compiled to CSS. It allows you to use variables, nested rules, mixins, functions, and more, all with a fully CSS-compatible syntax.

Sass helps keep large stylesheets well-organized and makes it easy to share design within and across projects.

Inside our React App we can use Sass module (npm install node-sass --save) and convert all of our CSS files into SCSS.

Basic syntax will be show on the Hands-on, for more in-depth understanding read the documentation on Sass website.

37 of 46

6

Basic routing

38 of 46

Basic routing

React Router, and dynamic, client-side routing, allows us to build a single-page web application with navigation without page refreshing as the user navigates.

React Router uses component structure to call components which display the appropriate information.

When not using React Router, App is often the highest parent component in React apps. With React Router, however, the Router component needs to be the highest parent.

39 of 46

Basic routing

Install React Router: npm install ‘react-router-dom’

Three main parts of React Router:

  • BrowserRouter - Actual Router component, highest parent in React App
  • Route - Component which will call render wanted component for specific path
  • Link - similar to <a> tag but prevents page refresh, used to create navigation links

Router has a lot more functionalities and you can read more here.

40 of 46

Basic routing

Implementation step 1 (index.js):

  • Import BrowserRouter and wrap your main App component with that component.
  • You can add alias to named import (as Router).
  • Now our main <App /> component is wrapped by <Router></Router> and on the whole scope of React app, router features can be used.

41 of 46

Basic routing

Implementation step 2 (App.js):

  • Import named export Route from ‘react-router-dom’.
  • Create Route components with path and component attributes.
  • Root path needs to have exact attribute.
  • Attribute path is used to defined name of path in the browser, and component is used to say which component needs to be rendered for actual route.

42 of 46

Basic routing

Implementation step 3:

  • Import named export Link from ‘react-router-dom’ in any component.
  • Create Link components instead of <a> elements, and add to=”” attribute to them.
  • Now when users click on specific Link component, the view for specific route will be rendered immediately.

43 of 46

7

Hands-on

44 of 46

Hands-on

45 of 46

8

Homework

46 of 46

Homework