React Flashcards

(195 cards)

1
Q

What is React?

Hint: Developed by Facebook in 2011

A

A javascript library for building fast and interactive user interfaces

React is a library NOT a framework

currently the most popular JS library for building UI

dominating frameworks for building UI (over angular and vue)

developed at Facebook in 2011

Expand job opportunities, know react!

Used by Facebook, Uber, Netflix, Twitter, Pintrest, AirBnB

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is every React application?

A

A tree of components

each component is independent (UI element)

can build components in isolation + combination for UI

UI elements connected together in a tree:

Navbar

Profile

Feed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a component?

A

a piece of the user interface

built indepently, isolated, re-usable

compose to build complex user interfaces

implemented as a Javascript class

Contains:

state (data to display)

render method (JS object maps to DOM)

Don’t work with DOM API in browsers

Each App:

contains root component

additional components are children

React app is a tree of components

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What do we no longer have to do when working with React?

A

only makes sure view is in sync with state

React is a library NOT a framework

No longer to write code to

query and manipulate DOM

attach event handlers to DOM elements

Why?
React reacts to state changes (virtual DOM) and automatically updates DOM

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a react element?

A

A plain javascript object that maps to DOM

not a real DOM object, just plain Javascript object represents DOM element

React keeps a lightweight representation of DOM in memory

when a change occurs, a new react element is generated

React then compares to real DOM and updates

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How is JSX compiled?

Hint: React.createElement ( )

A

we don’t directly use React from ‘react’ in JSX but…

When JSX code is compiled React.createElement ( ) is called

output of JSX expression is a React element

Ex. type: h1, etc. part of virtual DOM

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between React and Angular?

A

React is only a library that helps maintain the view in synch with DOM

Angular is a framework (complete solution)

React has small API to learn

calling HTTP services, routing requires 3rd party libraries (Express)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are two helpful extensions?

Hint: Simple React Snippets, Prettier

A

Prettier - helps fomat our code

React Snippets -

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the create-react-app command do for us?

A

all config is done for you!

Set’s up React Project:

lightweight server - allows us to host our react app during production

webpack - bundle code together into small packages to optimize load time

babel - compiler lets us write modern Javascript code that works in older browsersoverride settings/customize?

npm run eject

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is jsx?

Hint: Javascipt XML

A

syntax to describe what UI will look like

compiler (bable) takes jsx converts to vanilla JS (browser can understand)

in components use jsx and leave it to bable to call react

Ex. Babeljs.io - takes jsx converts to regular Javascript

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does npx eject do to our app?

A

allows us to customize configuration

hidden complexities (Bable, webpack, etc) removed

package.json adds dependencies

can add our own webpack, etc.

npm run eject

WARNING

Don’t do this unless you’re an advanced developer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is Mosh going to teach us about Full Stack architecture in this course?

A

He is going to show us how to talk to a Node/Express server

focus on frontend

node server running on different port

React app talk to (get / send) data + store in MongoDb

connect to a real Node/Express backend (get/store data in MongoDb)

code given is code created in Node course

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What will we learn in this course?

A

Build a real world video rental application

Feel confident building other applications on your own!

Topics:

Javascript - basics (take his other courses)

Components - building blocks of React

Tables - pagination, searching, sorting (common in apps)

Forms - validation (common in apps)

Routing - taking user between pages

HTTP Services - how to talk to backend services (data in MongoDB)

Auth - services from node backend (Node vs. Firebase)

Deployment -

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
  • *What** is Redux?
  • *Hint:** used in 50% of React Project
A

Used in more than half of React projects

Not every React project needs Redux

Focus on learning React FIRST

learn Redux NEXT

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are pre-requisites of learning React?

Hint: 3 months of Javascript programming

A

JS basics - teach how to think like programmer, solve programming problems

JS OOP - advanced topics

Basics:

Let / Const keywords

Objects

this

Arrow functions

Destructuring

Spread Operator

Classes

Modules

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the problem with this code?

Hint: var keyword

A

variable shouldn’t be accessible outside of a function (scope)

loop variable is accessible outside for loop!

var keyword accessible inside fn defined

Solution?

ES6 declaring variables

Let - only accessible inside block

const - only accessible inside block (constants_

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the difference between let and const?

Hint: scope limited to block, read only

A

const - cannot be redefined (read only)

not a variable, cannot be re-assigned

let - variable that can be defined

Use const vs let

use let only when you need to re-assign a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What should we know about objects?

A

accessing properties or methods:

dynamically - bracket notation

static - dot notation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How is the .this keyword diferent in Javascript than Java/C#?

A

doesn’t always reference current object

value of .this is determined by how a fn is called

if call a fn as a method in an object.this refers to that object

if call a fn as a standalone obj or outside a fn .this returns window obj (global obj)

in Java (.this) always references current obj

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do we bind .this to always reference the current object?

A

.bind( ) method

takes an arg (obj) that sets .this to point

value of this based on arg passed to .bind

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What should we know about arrow functions?

A

fat arrow between params and body of fn

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How does .this behave with arrow functions vs. anonymous functions?

A

arrow functions bind .this to current object

annonymous functions .this points to globl obj

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What did ES6 introduce as a new method in Arrays?

Hint: very useful in rendering lists in React

A

Map method of Arrays

Very useful for rendering lists in React

callback function transforms each element in array

takes one item at a time, returns a new item

returns a new array

Ex. ${} argument placeholder -> whatever put inside is dynamically rendered at run time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is object destructuring?

A

Modern JS feature seen in a LOT React apps

Need to extract value of properties and store in separate variables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
**What** is the **spread operator**? **Hint**: **Used** a lot in **React apps**
get every **item from an array** and **spread into a second array** ## Footnote **get each individual item in array** **can easily clone an array** **can apply spread operator to objects**
26
**What's** the **problem with this code**?
**To create** **another object** **Have to duplicate code** if **future changes**, have **multiple places to update** **Soln?** Classes (template) constructor takes parameters .this refers to current obj new operator is required
27
**How do** we use **inheritance in ES6**?
**in React** we **extend the base class** **Why?** **Many members** are **required in our components** (re-usable)
28
**How** do we **import a module in ES6?**
29
**What** are **named exports?** Hint: Named items exported from a module
**We can** export **one or more objects** from **a given module** ## Footnote **When what is exported has a name, called named export** **Ex. Teacher module has** **Teacher class & promote ()** **can export class or function**
30
**What** are **default objects?**
**If exporting** only a **single object (single class)** **Don't need curly braces** **add default keyword export syntax** **Ex.** Exporting the **Teacher class** in a module A class is **technically an object in Javascript** **Can have default export + named exports** **Default -\> import ... from '' ;** **Named -\> import { ... } from '';**
31
**Can** we **import both** the **default export and a named export**?
**Yes** Very **common in React** **99% of time** call { **component** } vs. **other named exports** in **React module**
32
What are **we going** to **build while learning components**?
**Pattern** behind **items in a shopping cart** **Render content dynamically** **Apply CSS dynamically** **reset quantity of items**
33
**How** do we **load bootstrap** in our **React app**?
**npm i bootstrap** **import**"**bootstrap/dist/css/bootstrap.css**"
34
**How** do we use **Simple React Snippets?**
**imrc** -\> creates an import statement **cc** -\> creates a component class
35
**How do we create** our first **React component**?
36
**How** can we **optimize this code**?
To **solve the return** ; **problem** instead of **using a we can use React.Fragment from React module**
37
**What i**s the **state member** of **a component**?
**an object** that includes **any data** the **component needs**
38
**How can we embed** an **expression in our components?**
**can return jsx expression from function** they're **compiled to JS objects**
39
**How can we set** a **component attribute**?
40
**How** do we **set class attributes**?
best to **use classes** for **style attributes (performance, maintainability)** How? **jsx compiled to javascript objects** **cannot use** **reserve keyword** *Class* therefore ***className* is used** **badge badge-primary m-2 (bootstrap classes)** **btn bnt-secondary btn-sm (bootstrap class)**
41
**How** do we **apply styles** to **React components**?
**best to use classes (performance, maintainability)** **advanced developer?** want to apply styles to only specific element
42
What are **inline styles**?
**apply styles to different elements** instead of **defining a style externally** can **pass a style object inline**
43
How can we **render component attribute classes dynamically**? **Hint**: if state= x, make button yellow, if state=y make button blue
**give an element** a **class attribute dynamically** **extract** to a **separate method** to **keep code clean**
44
**How** do we **render a list dynamically** in **React?**
**.map ( )** **takes arg** -\> maps to jsx -\> really just a React element **-\> compiled to JS object** WARNING each element in the list should have a unique ID so that react can respond to any changes in the virtual DOM add key = { id }
45
**How** can we **render a list conditionally**? **Hint:** Two ways
Create a **helper method** Use the **logical && operator**
46
**What** do **React elements have**?
**Properties** based on **standard DOM events** Ex. **onClick**, onKeyPress, **onKeyUp**, etc. pass **function reference** to **.onClick ( )**
47
**How** do we **bind event handlers**?
create a **constructor** call the **super ( )** **alt solution?** **Use an arrow function**
48
**How** do we **update** the **state** of a **React component**?
**.setState()** method from **React component (async method)** ## Footnote **calls render ( ) asynchronously**
49
**How** do we pass **event handler arguments** in **React**?
**.onClick ( )** must **pass a function reference** 1. Create a **helper method** - not ideal 2. Pass an **inline arrow function** - better approach
50
**How** do we **generate a table markup** using **shortcut?** **Hint**: table.table\>thead\>tr\>th\*4
zen coding
51
**How** do we **generate** a **table body** using **zen coding**?
tbody\>tr\>td\*4
52
**How** can we **create** a **React component** to **render the list of movies**?
53
**What** does a **real world application** **consist of**? **Hint:** Tree of Components
**React is a tree of components** **Compose components together to create a complex UI** **Very Important Topics** **After you'll have a deep understanding of React components** **Topics** you'll **use quite a lot** in **real world applications** **Learn**: How to **pass data between components in the tree** **Raise and handle events** **synchronize componts** **Functional components** **Lifecycle hooks**
54
**How** can we **optimize this code?**
**Compose elements together** Using an **array of components** in the **state object**
55
**How** can we **pass data** between **components**?
using **special JS object** called **props in each component** **external data is mapped** to a **React component's props object**
56
**How** do we **render content** inside a **React component?** ## Footnote **Hint: Pass data from Children to Virtual UI**
the **props.children** field each **react component** stores **data** in a **props object** **props.children** hold **subcontent** Ex. **Dialogue Box** componet with **content displayed**
57
**What** is a **very useful tool** for **debugging react applications**?
**Extension** for **Chrome, Firefox** ## Footnote **React Developer Tools**
58
**What** is **$r in React Developer Tools**?
**allows** us to **work with instance of any Component** on **page in console**
59
**What** is **$0 in react developer tools?**
helps us **build and debug react applications** Keep **React Developer Tools** in **your toolbox** **allows us** to **work with elements** (like buttons)
60
**What** is the **difference** between **props and state** in a **React component**?
**props** includes **data** we **give to a component** inputs to a **component** **some components get all data from props, no state** **read only, cannot change input to component inside component** **purly input to component, cannot modify input** **extract props input and store in state to work with it** **state** includes **private or local data** to component other components **cannot access state** data **completely internal,** **cannot access outside** invisible to **other components.** Ex. state obj in counters -\> internal to counters
61
**What** is a **very important rule of thumb** in **React applications**?
The **component** that **owns a piece of the state** **should be** the **one modifying it** **Ex. adding/removing** a **counter** from the **counters array** should be **done by counters component** vs. **counter component** **BUT** **Delete button is on counter component** **SOLN?** **Have counter component raise an event, counters component will handle it** **pass reference to parent method using props.child to our child component**
62
**What** is a **single source of truth**?
**React component** has **local storage (state)** **Parent** also has **local storage** **Soln?** **Remove** the **local state** from **components** **Keep** a **single source of truth**
63
**What** is a **controlled component**?
remove **local state object** receives **data only via props object** **raises** **events** when **data needs to be change** **component** is **entirely controlled** by **its parent**
64
**What** is a **"no-no" in React**?
**updating** the **state directly** Ex. updating the **counters[0].value++ directly** must **clone object,** use **setState ( )** replace object
65
**How** can we **update the state** of a **React Component**? **Hint**: Update **state of parent** w/ **stateless child**
**DO NOT** update **state object directly** **Clone** **state object,** modify **set state to this new object**
66
**How** can we **create a tree of components**?
1. Make **App** our **root component** in **Index.js** **ReactDom.render** () 2. **Create a hierachy** in our App.js file w/ **NavBar** and **Counter** Components 3. Wrap in React.Fragment when returning **multiple components from App**
67
**How** can **we build** our UI **look / feel**?
**Bootstrap**! Grab nav bars, lists, etc.
68
How can **share data** / **keep two components in sync** when there is **no parent-child relationship (props)?** **Hint:** How can we **display # counters** in **Navbar** w/o a **props object**?
**Lift the state up** **Make all elements share same parent (App)** **Give access to all children (via props)** **Ex**. Move state of **counters to App** component vs. **Counter**
69
**How** do we **lift up the state**? **Hint**: **Move** state from **child components** to **Root App**?
1. **move** **state** and **all methods** that **modify state** to **parent (App component)** ## Footnote **2. in App component - handle events raised by components (onDelete, onReset, onIncrement) w/ handleDelete, handleReset, handleIncremement**
70
**What** is a **stateless functional component**?
**Component** **isn't storing state** **Component doesn't have event handlers** All **data / event handlers** done in a **parent class** **convert component** into a **stateless functional component** **How?** **Use a fn that returns a React element vs. a class with a render ( ) method** **sfc -\> shortcut for a functional component**
71
**What** are the **various** **lifecycle phases** our **components go through**?
**Lifecycle hooks** **Special methods** we can **add to our components (classes)** **React** will **automatically call these methods** **allow us** to **hook into certain moments** of a **component lifecycle** **90% of time, will use listed methods** **cannot use in stateless functional components** **Ex. Call AJAX after componentDidUpdate ( )** **MOUNT** An **instance of component is created** and **inserted into DOM** **constructor ( ) -** called once during instantiation, set state directly (initialization) based on props **render ( ) -** returns a react element that represents the virtual DOM, react then renders it in actual DOM **componentDidMount ( ) -** called after component rendered in DOM, make AJAX calls to get server data (setState( ) ) **UPDATE** **when state or props of a component** is changed, these **two methods called in order** **render ( ) -** setState ( ) calls the render( ) method, component tree is rendered (virtual DOM updated) compares virtual vs. old virtual DOM, updates accordingly **componentDidUpdate ( ) -** called after update (new state or props) compare new state or props with old state or props, if change, can call AJAX on server **decide whether to make an AJAX call based on changes in state or props.** **UNMOUNT** **component removed** from **DOM** **componentWillUnmount ( ) -** called before component is removed from DOM, can do a cleanup (remove timers/listeners) to avoid memory leaks
72
**What** are the **MOUNT** **lifecycle hooks**?
constructor ( ) **initialize state via props** render ( ) **put componet in DOM** **all children rendered recursively in virtual DOM (new copy)** componentDidMount ( ) **AJAX calls to server**
73
**What** are the **UPDATE** **lifecycle hooks**?
**UPDATE** **state** of **component changed** or **new props given** **componentDidUpdate ( )** - new state or props \***if changed**, make another **AJAX call to update date** (optimization technique)
74
**What** is the **UNMOUNT** **lifecycle phase**?
**componentWillUnmount ( )** called **just before** component is **removed from DOM** **allows us to do cleanup** **Ex. remove listeners or timers (reduce memory leaks)** **entire component tree** is **re-rendered** **(new copy of virtual DOM)**
75
What happens when the render ( ) method is called during an UPDATE lifecycle hook?
When state is updated using setState ( ) a call to the render( ) method happens **STEPS:** **entire component tree** is **rendered** a **new copy of the virtual DOM** is **created** **React** compares **new virtual DOM** to **old virtual DOM** **updates changed components** accordingly (not others)
76
**How** do we **add the decrement button**?
77
**How** do we **raise and handle** **events**?
**Conceptually:** **Counters** component is **raising an event** onDecrement **App** component is **handling event** using handleDecrement **Implementation:** **using props** to **pass function references**
78
What are **we going to build**?
**writing clean code, refactoring:** Pagination Filtering Sorting Mosh's favorite section!!
79
How do we **design a new feature / component** in React?
1. What is the **interface like**? (Input/Outputs) 2. What **data does it need**? (props) 3. What **events will it raise**? (handlers) Ex. Pagination Inputs - totalNumberOfItems, pageSize
80
How do we **render data** in our **pagination component**?
Don't want to **change original list of movies** **Solution?** **Create a copy** of the **state data** as we **paginate, search, filter** want a **separate array**
81
**How** do we **validate props** passed to **components**? **Hint**: npm i prop-types@15.6.2
Good practice to use **PropTypes** for **re-usable components** Can look at PropTypes to figure out props, type, required/optional
82
**What's** the **problem** with **how this code is organized**? Hint: Mixed levels of abstraction
**We have**: **ListGroup** - custom component (details in separate module) **Table** - generic component with **lots of details** **Pagination** - custom component (details in separate module) **Components** that are **high level (abstract)** and **table (low level - detailed) are mixed** No symmetry **Soln?** Move **details** of moviesTable to **a new file** **In movies**, keep **only high level components** **(ListGroup, MoviesTable, Like)**
83
**How** do we **implement filtering** in our **React app?**
EventHandler **(handleSort)** **calls setState** -\> **re-render ( ) -**\> **display to user (filter, sort, paginate)** **underscore** has **\_.orderBy method**
84
**What's** the **problem with this implementation**?
if we **re-use movie table** on **another page** will have to **duplicate sorting logic all over** **soln?** **Technically, this logic belongs to movieTable component itself** **in MoviesTable add a function to determine sort order**
85
**What's the problem** with the **current implementation**?
If we r**e-use MovieTable, currently it's okay** But **if we create another table (ex. customers)** will have to **duplicate logic for sorting** **Soln?** **Extract component** (tableHeader) that **encapsulates logic** can **re-use logic in any table**
86
What's the **problem with this code**? **Hint:** Mixed levels of abstraction
**High level component** (TableHeader) table body has all **details of how to render body** **very ugly** **Soln?** We need a component like TableBody to abstract the details
87
**How** do we **refactor this code**?
88
How can we **refactor this code**?
it's **polluting our render ( ) method** ## Footnote **extract into a separate method**
89
**How** can we make this **code cleaner**? **Hint:** destructure props
fn takes props object **destructure initially as argument comes in** get what we need **without declaring a constant**
90
What did we **learn in this section?**
**Should be able to apply to design, build new component** Component Design **Input/output + events raised** ( component interface) **Re-usable components** (extracting table header, body, etc.) **Refactoring** (destructuring props) **Writing clean code**
91
**What** are we **going to do?**
**Add routing to our application**
92
What **don't we have** in **React**? Hint: Routing
**Routing** React is **only responsible for rendering view** (nothing more) Must install a library **npm i react-router-dom** **import BrowserRouter (wraps history obj from DOM in tree)** **wrap App inside** **add Route obj to App.js for paths** \*implementation of react router for dom
93
How do we **implement routing in React?**
**Route object** takes the path (url path) renders component based on path **Ex**. **/Products** will render **Products component**
94
What is the **Switch object**?
import { Route, Switch } from "react-router-dom"; will render first route that matches path **NOTE** order routes from most specific to general
95
What are **Single Page Applications** (SPAs) ? **Hint**: localhost (HTML page), bundle (combined all JS code)
When click on pages, **don't have a full reload** (single page application) **Problem:** In large enterprise application **DO NOT** want to **download HTML** and **all JS combined (bundle)** everytime user **navigates to a new page!** **Solution:** Single page application **Do not have** a **full reload** of **HTML and JS bundle** When **user navigates** from **one page to another** (instead of **reloading entire page** with all assets) **only update content** **Ex. Gmail** - entire page is not reloaded as you click between emails
96
How do we **convert our React app** into a **single page application**?
**Anchor text** is the **clickable text** in a hyperlink In our current implementation, our clickable text calls our server (redownloading JS bundle and HTML document everytime) **Soln?** import { Link } from 'react-router-dom' **component replaces component** **prevents additional HTTP request to server** **tells UI** DO NOT re-**download HTML page** and **JS bundle** **only update the content** **Great!** **No new requests to server every time user navigates pages**
97
What is a **Route component**?
A **wrapper around the component we pass** automatically **injects three props** into **component** (history, location, match) **history** - work with history object in browser **location** - where app is now (/products, etc) **match** - info on how url matched path (params, path, url)
98
**How** can we set **additional props** when **using a route in React?**
use render ( ) attribute vs. component attribute set render attribute to arrow fn Ex. () =\> additionalPropParams="" \> arrow fn returns Products component w/ props
99
What's the p**roblem here**? **Hint:** other props missing (history, match, etc.)
**Solution:** Pass **props in arrow fn** as args **use spread operator** and jsx will **add props to component**
100
**How** do we **define route parameters in React**?
**/:param** Match prop contains route params can **read route params** passed to **component from match** **{this.props.match.params.id}**
101
How do we **stop our pages from doing full page renders?** **Hint:** convert to **single page application?**
**replace** with **replace** href= with 'to' **import { Link } from 'react-router-dom';**
102
**How** do we **make parameters optional?**
Generally, **avoid optional parameters (put in query string)** regex in Javascript - add a **? to parameter (make it optional)** can **access params using props** -\> **destructur to get match prop** Ex { match.params.year }
103
**What** are **query strings**?
What we **append to a URL** using a **quesiton mark** added to **location object (prop)** in **react components** instead of **extracting string**, **splicing** and **reading values**... **npm i query-string** **very popular package for working with query strings**
104
**How** do we **extract query string** params **from a route**?
**npm i query-string** **queryString.parse(location.search)** **location.search** = where query string params are stored
105
How can we read **route parameters** **passed to a component**?
object adds history, location, match props match props stores route parameters {this.**props.match.params.**id }
106
**How** do we **re-direct a user** to a **new page or a page not found?**
import { Route, Switch, Redirect } from "react-router-dom";
107
Where are **route parameters** vs. **query string parameters?**
**Route Params (Match prop)** {**match**.params.routeParameter) **Query String Parameters (Location.search Prop)** don't want to manually **read string, parse, etc.** use npm package helper instead! **npm i query-string** queryString.parse**(location.search)**
108
**How** do **we re-direct a user** when they **click a button** or **submit a form**? **Hint:** Programmatic re-navigation
**history.push ("path", [state])** redirects to "path", pushes [state] to history (for back navigation) ex. this.props.history.push("/products") **redirects to products page, saves current page in history** **Props - history object** contains **useful methods** for **navigation** **goBack, goForward, Push, Replace** **push()** add new address in browser history (can go back) **replace** () replaces current address, no history cannot go back **(often used in login pages)**
109
**How** do we **implement nested routing?**
Ex. We have a **navigation bar in header**, **side navigation bar** (second navigation) component can be used anywhere!
110
**How d**o we **extract query string parameters?**
url/?**queryStringParams** **accessible in location.search field** **const { destructureQueryString }** = queryString.parse(**location.search**) **location is a prop** inserted by **Router into our component**
111
**How** do we **add routing** to our **vidly application**?
npm i react-router-dom add to index.js (wrap App component) add to App.js pointing to our components wrap in component to ensure not first matching / caught each url add where necessary
112
**What** are we **going to build in the forms section?**
**Almost every application needs some kind of form** **Login Form** **Registration Form** **Add/Edit movies Form** **Search Box**
113
**How** do we **properly submit a form in React?**
**By default,** **submitting a form** makes a **full call to server** (**re-download HTML, JS bundle**) **This is not the behavior we want** **Soln?** **Every form has an onSubmit ( ) event** **define custom handler (handleSubmit)** **preventDefault ( ) behavior** no longer have a full page reload
114
**How** do we **get the value of our input field in a form?** ## Footnote **Hint: Refs solution**
**DO NOT** work with **document (DOM) model directly** **React** provides an **abstraction of DOM elements** **Soln?** **username** = **React.createRef();** set input field tag to **ref={this.username}** const username = this.**username.current**.value; returns actual DOM element, can get value **NOTE** **There** is a **better way** **Minimize** use of **ref** **only use with:** set focus on field, animations, third party DOM libraries
115
**How** do we get **data from an input field?** **Hint**: Controlled elements
a **form gets data from Server**, **stores in state object** We are **not using a server** but we can **store input data in state object** **Best practice:** **keep state object** and **input in sync using onChange ( ) event that each input field raises when user types** How? **input field** has a **onChange( )** event raise the **onChange( )** event **good time** to get user typing and update state whenever **user types something** **handleChange ( ) by setting state**
116
**What** is a **controlled element**? Hint: input fields, headers, anchors have their **own state (data)**
**HTML Elements** input fields, headers, anchors **by default** have their **own state (data)** A **controlled element** (like **stateless functional component**) **Is one without state, data is controlled via props** Ex. Using Props to set value (state) of Input field **WARNING** **value** property of **controlled element** cannot **be null** (or errors occur) **SO** must **set to an empty string** or **some value** from **the server (initially)**
117
**What's** the **problem** with **this code?**
**it repeats** a lot of markup/fields ex. name is repeated, etc. **SOLN?** **Extract input** into a **re-usable component** **pass args via props** **reduces bootstrap markup from login form** **makes our code cleaner**
118
**How** do we **implement validation** on our **input field?**
Add an **error object** to our **loginForm state** create a **helper method validate ( )** called upon **handleSubmit** **validate ( )** returns an **error object** **.setState ( errors )** =\> **re-render w/ errors**
119
**What** is a **basic implementation** of **validation in forms?**
use npm joi-browser for actual validation
120
**How** do we **validate forms using joi in React?**
**npm i joi-browser**
121
**How** can we **refactor this code?** ## Footnote **Hint: Extract re-usable validation logic**
**validate and validateProperty are reusable** **extract** into **form.jsx** **handleSubmit ( ) is partially reusable** **extract into form.jsx** **handleChange ( ) is reusable** **extract into form.jsx**
122
**How** can **we refactor** the **render method**?
**submit button is re-usable** **extract** into form.jsx **input field is re-usable** extract into form.jsx
123
**How** do we **refactor this?**
use the **rest operator and spread operator** can automatically set any **additional attributes in our props**
124
How **do we make** this **method generic**? **Hint**: change from **dot notation** to **bracket notation**
**dot** **variable = object**.**targetProperty** **bracket** **variable = object** ['**targetProperty**'] if we give each object a name property and set to a string we can access **e.currentTarget.name while resolves to a string**
125
How do we add a **movie form to our app?**
126
**How** do we **add** a **search input to our App?**
127
How can we use a **fake backend in our APP?**
JSON Placeholder provides endpoints (REST) for us to access can send HTTP request (GET, POST, PUT)
128
What is **React only?**
A l**ightweight library** Only care about making sure **component state** is in synch with DOM can use any library to do HTTP requests **To make HTTP request:** **Fetch API** in most modern browsers **jQuery AJAX** a popular library that uses asynch javascript XML for fetching data from server **Axios** Mosh's preferred way for HTTP requests in React
129
**How** can we make **HTTP requests** in our **React applications**? **Hint**: Axios
npm i axios **To make HTTP request:** **Fetch API** in most modern browsers **jQuery AJAX** a **popular library** that uses **asynch javascript XML** for **fetching data** from server **Axios** Mosh's preferred way for **HTTP requests in React** * Make **XMLHttpRequests** from the browser * Make **http requests** from **node.js** * Supports the **Promise API** * Intercept **request and response** * **Transform request** and **response data** * Cancel requests * Automatic transforms for JSON data * Client side support for protecting against XSRF
130
**Why** do we **need promises**? **Hint:** axios.get ('api/endpoint') returns promise
**Object** that **holds result of async operation** (complete in future) **HTTP request** has a **delay before result** 5ms, 1 sec **Promise** holds result of **async operation** **Pending** **Resolved** **Rejected** **Resonse object?** **Has fields including data (from Api endpoint)**
131
**How** do we get the **result** of our **async operation** **(HTTP GET request)**?
132
**How** do we **call Server** to **populate posts** in our **React app?** ## Footnote **Hint: HTTP GET request**
const **{ data: posts }** = await **axios.get(apiEndpoint)** **ComponentDidMount ( )** called **after component** is **rendered in DOM** call **server, get data, rerender** / **displace state from server**
133
**How** do **we perform** and **HTTP POST request**? **Hint:** axios.post (apiEndpoint, resource)
134
**How** do we **execute a POST request** using axios?
135
**How** do we **execute** a **DELETE request**? **Hint**: axios.delete(endPoint/resourceID)
136
**What** are **pessimistic updates**? **Hint:** GET, POST, DELETE
**Call server first (takes time)** **Then, update state / re-render DOM (UI)** This **causes a delay** Ex. it takes 1 second for DELETE, POST, etc. to show on DOM Pro? If error on
137
**What** are **optimistic updates**?
**gives user** the **illusion of a fast application** still **takes time for server** **Optimistic Update:** **assume server** will **succeed** **First, Keep reference to previous state** **Then,** update **state** **Finally,** call **server (wrap in try/catch)** **IF ERROR,** update state to previousState \*can **revert UI** state if server fails Revert? **Easy** - we always **save reference to previous state** **(never update state directly)**
138
What **types of errors** do we have in our **React Apps**? **Hint**: Expected vs. Unexpected
**exception object** generated **(two properties** - **req & res**) **Expected -** server has predicted + handled these errors **CLIENT ERRORS** **404:** Resource Not Found (deleted item already deleted) **400**: Bad Request (server data validation fails, form field failed) \*display **specific error message** to user **ex.request** = null (if cannot succesfully **submit req to server**) **ex.response** = NOT null (if get a **response from server**) **Unexpected** - shouldn't happen under normal circumstances **SERVER ERRORS** ex. **network down, server down, db down, bug in app code** **ex.response = null (no response from server)** \***log them** (review in future), display a **generic error message**
139
How can we **differentiate between** whether the **error is expected or unexpected**?
**exception object** ex. request ex. response if server down, etc. won't get a response (field will be null)
140
How do we **initialize a component**?
using **{ } syntax** Can **initalize component attributes** **each component has a JS object member called props which includes all attributes initialized** **ex. initialize Counter component w/** key = {counter.id} **value**={counter.value} **selected**={true} **counter.props** -\> value & selected will be properties of JS object **(Component props obj)**
141
What is **axios.interceptor**?
**Can** intercept **request & response** if we have **unexpected error,** can **log and display friendly error message** Can **intercept** request **before going out** Can **intercept** response **coming in**
142
**How** do we **handle unexpected errors**?
with interceptor handle **unexpected errors globally**
143
**When** do we **need try catch blocks**?
**Only** when **doing something specific** as a **result of the failure** **reverting UI** **expected error occured** **DO NOT NEED** in **didComponentMount ( )** **leave handling of unexpected errors**
144
What's the **problem with this code**? **Hint:** it's not re-usable, it is polluting App code
**extract** into **HTTP module** **can import** into **new projects, etc** **hide axios** behind **http module**
145
**How** do we **display Toast notifcations**? **Hint:** npm i react-toastify
**import { ToastContainer } from 'react-toastify';** **import 'react-toastify/dist/ReactToastify.css';** add to **App.js** under replace **alert** with **toast.error ( ) in httpService module**
146
**What** is **Sentry**? **Hint**: logging as a service
$**npm install** **--save @sentry/react @sentry/tracing**
147
Why does **Mosh like Sentry**? **Hint:** can log, view breadcrumbs, assign to devs on team, etc.
**very powerful tool (team)** can **log, view** **unexpected errors**, assign **devs on team, view progress, etc.** **details on unexpected errors** **http://programmingwithmosh.com/tools (2 months free $52 value)** **Breadcrumbs** -\> **shows where button was located** -\> **click event** XML etc. can **assign issues to developers on the team**, etc
148
**How** do we **delete a movie** from **React App** using our **Node backend**?
149
**How** can we **fill our form with data** from our **backend (node/express/mongoDb)**?
**refactor** to **populate genres() and populate movies ( )**
150
**How** can we **refactor this**?
**code is telling a story** **when** looking at **componentDidMount ( )** **can tell two things** should happen **(populating genre, populating movie)**
151
**How** can we **refactor this code**?
152
**What are we learning** in the **Authentication and Authorization sections**?
Add **ability for users** to **register, login, logout** **JSON web tokens** **(Calling protected API endpoints)** that **require user to be logged in**, or **have certain permissions** **(Showing / Hiding Elements)** **​depending** on **user permission** **(Protecting Routes)** users **cannot navigate** to **certain parts of application** if **not authenticated or authorized**
153
**How** do we **register a user**?
**create** a **userService.js** **import** **userService** in **registerForm.jsx**
154
**How** do we **handle errors** in the **registration form**?
wrap **call to server** in a **try-catch block**
155
**How** do we **log in** a **user in** our **React App**? **Hint:** call the **auth endpoint** (**node/express/mongoDb**)
**send post request** to our **auth endpoint (api/auth)** if a **valid user / password** is given, **generateAuthToken() called** (privateKey, user) **JSON webtoken** sent in **response to client** **token stored in header section** **next request jwt.verify will check JSON web token w/ privatekey**
156
**How** do we **handle errors in Login form**?
157
**Where** do we **store JWT on browser**?
**response.body sends jwt** can store in local storage **Local storage?** every browser has a small little database Can store key-value pairs Can get JWT from body of response
158
**What** is a problem **React developers face**?
**response object (from server)** **doesn't have custom header** w/ **x-auth-token** **Soln?** in Node backend **.header("access-control-expose-headers", "x-auth-token")**
159
How do we **log a user in upon registration**?
**get the response from server** header('x-auth-token) store **x-auth-token** in **local storage** after registering user
160
**How should** we **organize our import statements**?
**organize:** third party library components css files
161
**How** do we **get the current user**?
during **App.componentDidMount ( )** get **JWT from local storage** **decode JWT** Set **User to App.state**
162
**How** can we render the **login / register links** in our **nav bar conditionally**?
**set user** in **App.state** pass **user object in props to NavBar**
163
**What's** the **problem with this code**? **Hint**:
**Homepage** only **rendered once** during **componentDidMount ( )** instead of **redirecting user,** must **do a full page reload** **How?** window.location = '/' cause a full page reload App will be re-rendered
164
**How** do we **implement Logout?**
165
**How** do we **refactor** our **login, logout, etc.**? **Hint**: create **authService.js** to **handle JWT**
166
**How** do we **call protected API endpoints**?
get **jwt from local storage** send in **request header w/ axios**
167
What is a **common and dangerous design issue?**
**bi-directional dependency** have a dependency on **authService** and **httpService** **which module is a core module?** **httpService** if we cannot make http connections to backend, authentication doesn't make sense authentication should be on top of httpService
168
How do **we get rid** of this **bi-directional dependency**?
reverse the dependency **have auth service give jwt to http module** vs. **http module requesting authService to give jwt**
169
**How** do we **hide elements from the UI** if a **user is not given permissions?**
**Example** Hiding a button on the movies page **Solution** Pass user obj as a prop to movies component conditionally rende**r HTML content based** on JSX expression **Hint** Inside a route, pass additional props render={props =\>
170
**How** do we **protect routes** from a **user without a valid jwt**?
Make **details page accessible** only if **logged in with jwt** **App.js**
171
How do we **refactor this code?**
Create ProtectedRoute.jsx (common component) Have ProtectedRoute render a Route component
172
**How** do we **create a protected Route**?
Create **protectedRoute.jsx** component (sfc) (common folder) **Return JSX** for **Route w/ path**, render method **(JS conditionally render component** based **on props** **when we use Route component, we supply path and either the render method or a component** **possible for component to be null (in protected route)** **make it conditionally return the render ( ) method**
173
**How** do we **re-direct a user** to the **previous page** they were on before **reaching a protected route** and being **required to login**?
Can **pass an object** to **react-router** component **Pass the location object from props** **Router** wraps **route w/ 3 props** **history, location, match** **location.match** attribute **holds path** **Redirect component has an attribute called "state"** **that "state attribute" can have a sub attribute - "from"**
174
**How** do we hide the **delete button** in our **movies table if a user isn't logged in?**
use authService to getUser
175
**What** are we **learning in deployment**?
**Environment variables** setting **development, test, production** level environment variables **Production Builds** optimize code for delivery to any servers **Deploy to Heroku** cloud service
176
**What environment** does **every application go through**? **Hint:** Development, Test, Production
**Development, Test, Production** **development environment variables** **test environment variables** **production environment variables** **sometimes** we want **different variable values** in **each environment** Ex. **Development** - want a fake backend service, **Production** - real backend service
177
**What** is **process.env**?
**console.log(process.env)** **Process Object:** **an object** **represents the current process** **env is a property** of **this object** **env represents all environment variables** **env variables** can be **set in terminal** or from **.env file**
178
**What happens** to **expressions that reference environment variables** at **build time**?
are **replaced by actual value** of **environemnt variable at build time** **npm start** initiates **build process** **all environment variables stored directly in shell or in config files get extracted and wherever process.env.REACT\_APP\_VARIABLE value is inserted**
179
**What** does **npm start give us?**
A d**evelopment build** that **isn't optimized** Why? Because JS bundle generated includes additional code for debugging we don't want this in production **Solution?** $npm run build gives us a production build
180
**What** does **npm run build give us**?
**npm run build** **gets production environment variables** A **production build** that **is optimized** can **basically take build folder** (optimized version of code) and **send** to **web server using FTTP**
181
**What** is **mLab**?
**Used** to **deploy MongoDb in the cloud**
182
**How** do we **deploy our backend** to **heroku?**
**https://peaceful-ridge-03071.herokuapp.com/** name of our application (in Heroku) address of application on Heroku frontend should send requests to this address **https://git.heroku.com/peaceful-ridge-03071.git** git repo at address (continuous integration) can push local code to this new repository Heroku will download latest source code, build it and push to address
183
**What** are **higher order components?**
**an enhancer component** adds functionality take a **component** return a **new component** (enhanced) w/ **added functionality** **How?** Takes an **existing component** as an argument returns an **enhanced component** (component wrapped) **Naming Convention?** withFunctionalityName
184
What are **hooks?**
**functional components were stateless** class components - state, lifecycle methods had to use classes for implementing state and lifecycle methods **React 16.8 new feature:** can **build functional components** with **state and lifecycle hooks** **Why?** classes are **hard to understand**, syntactic **sugar over prototypes** **this keyword is confusing** (have to use it with class components) **class components require boiler plate** don't have to call super (props) no reference to .this **Now?** can create powerful functional components code is cleaner
185
**What** is the **useState ( ) hook?**
**returns an array with two items** **value of counter** **function** for **updating value** **pass any initial value (number, object, string)** **cannot call hooks...** **inside loops, conditions, nested functions** **cannot call in if statement**
186
**What** is the **problem with lifecycle methods** in **class components?**
**logic gets spread around** some logic in componentDidMount() other logic in componentDidUpdate()
187
**What** is the **useEffect hook?**
**useEffect ( )** **evertime it receives new props or state changes, re-renders** **add second arg...** **list of dependencies** **re-renders everytime dependencies are updated** **allows** us to **hook into all three lifecycle** methods in **fn componets** **componentDidMount ( )** **componentDidUpdate ( )** **componentWillUnmount (.)** **can return a fn for cleanup** **pass an empty array so it's not called everytime a change occurs**
188
**What** is the **benefit of a custom hook?**
can **extract common logic** and **pass to multiple components**
189
**How** can we **fetch data with a hook?**
190
**How** do we **pass objects down** via **context in class components**?
**createContext ( )** returns a **context object** store in **Pascal variable** **Context.Provider** **regular react** component **takes prop (value)** can **pass objects down** via this prop **Consume context** expects a function (pass lambda expression)
191
**How do we set** the **context type in a class component?**
can use context to make decisions ## Footnote **set static property (static contextType = UserContext)**
192
**How do** we use **context in functional components?**
**useContext hook in React** **pass context as argument** **don't have a context consumer component underneath** **makes hierarchy cleaner**
193
**What is difference** between **context** in **functional components vs. class components?**
**Class components** have to use a consumer component have to provide a function makes code noisy **Functional components** all we had to do was use hook prefer functional components to class components
194
**How** do we **pass down a method** in our **context tree** to **update context?**
**change structure of context object** **change object passing down to (include handleLogin)** **update state by calling onLoggedIn (passed from context)** **any component can access this method** **as state us updated, so will context** **all consumers will be notified (MovieList, etc)**
195