React Flashcards

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

domimating 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 isolate + combine 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
Q

What is the spread operator?

Hint: Used a lot in React apps

A

get every item from an array and spread into a second array

get each individual item in array

can easily clone an array

can apply spread operator to objects

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

What’s the problem with this code?

A

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

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

How do we use inheritance in ES6?

A

in React we extend the base class

Why?

Many members are required in our components (re-usable)

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

How do we import a module in ES6?

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

What are named exports?

Hint: Named items exported from a module

A

We can export one or more objects from a given module

When what is exported has a name, called named export

Ex. Teacher module has

Teacher class & promote ()

can export class or function

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

What are default objects?

A

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 ‘’;

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

Can we import both the default export and a named export?

A

Yes

Very common in React

99% of time call { component } vs. other named exports in React module

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

What are we going to build while learning components?

A

Pattern behind items in a shopping cart

Render content dynamically

Apply CSS dynamically

reset quantity of items

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

How do we load bootstrap in our React app?

A

npm i bootstrap

importbootstrap/dist/css/bootstrap.css

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

How do we use Simple React Snippets?

A

imrc -> creates an import statement

cc -> creates a component class

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

How do we create our first React component?

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

How can we optimize this code?

A

To solve the return ; problem

instead of **using a

we can use React.Fragment from React module**

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

What is the state member of a component?

A

an object that includes any data the component needs

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

How can we embed an expression in our components?

A

can return jsx expression from function

they’re compiled to JS objects

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

How can we set a component attribute?

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

How do we set class attributes?

A

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)

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

How do we apply styles to React components?

A

best to use classes (performance, maintainability)

advanced developer?

want to apply styles to only specific element

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

What are inline styles?

A

apply styles to different elements

instead of defining a style externally

can pass a style object inline

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

How can we render component attribute classes dynamically?

Hint: if state= x, make button yellow, if state=y make button blue

A

give an element a class attribute dynamically

extract to a separate method to keep code clean

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

How do we render a list dynamically in React?

A

.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 }

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

How can we render a list conditionally?

Hint: Two ways

A

Create a helper method

Use the logical && operator

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

What do React elements have?

A

Properties based on standard DOM events

Ex. onClick, onKeyPress, onKeyUp, etc.

pass function reference to .onClick ( )

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

How do we bind event handlers?

A

create a constructor

call the super ( )

alt solution?

Use an arrow function

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

How do we update the state of a React component?

A

.setState() method from React component (async method)

calls render ( ) asynchronously

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

How do we pass event handler arguments in React?

A

.onClick ( ) must pass a function reference

  1. Create a helper method - not ideal
  2. Pass an inline arrow function - better approach
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

How do we generate a table markup using shortcut?

Hint: table.table>thead>tr>th*4

A

zen coding

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

How do we generate a table body using zen coding?

A

tbody>tr>td*4

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

How can we create a React component to render the list of movies?

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

What does a real world application consist of?

Hint: Tree of Components

A

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

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

How can we optimize this code?

A

Compose elements together

Using an array of components in the state object

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

How can we pass data between components?

A

using special JS object called props in each component

external data is mapped to a React component’s props object

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

How do we render content inside a React component?

Hint: Pass data from Children to Virtual UI

A

the props.children field

each react component stores data in a props object

props.children hold subcontent

Ex. Dialogue Box componet with content displayed

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

What is a very useful tool for debugging react applications?

A

Extension for Chrome, Firefox

React Developer Tools

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

What is $r in React Developer Tools?

A

allows us to work with instance of any Component on page in console

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

What is $0 in react developer tools?

A

helps us build and debug react applications

Keep React Developer Tools in your toolbox

allows us to work with elements (like buttons)

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

What is the difference between props and state in a React component?

A

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

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

What is a very important rule of thumb in React applications?

A

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

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

What is a single source of truth?

A

React component has local storage (state)

Parent also has local storage

Soln?

Remove the local state from components

Keep a single source of truth

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

What is a controlled component?

A

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

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

What is a “no-no” in React?

A

updating the state directly

Ex. updating the counters[0].value++ directly

must clone object, use setState ( ) replace object

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

How can we update the state of a React Component?

Hint: Update state of parent w/ stateless child

A

DO NOT update state object directly

Clone state object, modify

set state to this new object

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

How can we create a tree of components?

A
  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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

How can we build our UI look / feel?

A

Bootstrap!

Grab nav bars, lists, etc.

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

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?

A

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

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

How do we lift up the state?

Hint: Move state from child components to Root App?

A
  1. move state and all methods that modify state to parent (App component)

2. in App component - handle events raised by components (onDelete, onReset, onIncrement) w/ handleDelete, handleReset, handleIncremement

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

What is a stateless functional component?

A

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

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

What are the various lifecycle phases our components go through?

A

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

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

What are the MOUNT lifecycle hooks?

A

constructor ( )

initialize state via props

render ( )

put componet in DOM

all children rendered recursively in virtual DOM (new copy)

componentDidMount ( )

AJAX calls to server

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

What are the UPDATE lifecycle hooks?

A

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)

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

What is the UNMOUNT lifecycle phase?

A

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)

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

What happens when the render ( ) method is called during an UPDATE lifecycle hook?

A

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)

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

How do we add the decrement button?

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

How do we raise and handle events?

A

Conceptually:

Counters component is raising an event onDecrement

App component is handling event using handleDecrement

Implementation:

using props to pass function references

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

What are we going to build?

A

writing clean code, refactoring:

Pagination

Filtering

Sorting

Mosh’s favorite section!!

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

How do we design a new feature / component in React?

A
  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
Q

How do we render data in our pagination component?

A

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
Q

How do we validate props passed to components?

Hint: npm i prop-types@15.6.2

A

Good practice to use PropTypes

for re-usable components

Can look at PropTypes to figure out props, type, required/optional

82
Q

What’s the problem with how this code is organized?

Hint: Mixed levels of abstraction

A

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
Q

How do we implement filtering in our React app?

A

EventHandler (handleSort)

calls setState -> re-render ( ) -> display to user (filter, sort, paginate)

underscore has _.orderBy method

84
Q

What’s the problem with this implementation?

A

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
Q

What’s the problem with the current implementation?

A

If we re-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
Q

What’s the problem with this code?

Hint: Mixed levels of abstraction

A

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
Q

How do we refactor this code?

A
88
Q

How can we refactor this code?

A

it’s polluting our render ( ) method

extract into a separate method

89
Q

How can we make this code cleaner?

Hint: destructure props

A

fn takes props object

destructure initially as argument comes in

get what we need without declaring a constant

90
Q

What did we learn in this section?

A

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
Q

What are we going to do?

A

Add routing to our application

92
Q

What don’t we have in React?

Hint: Routing

A

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
Q

How do we implement routing in React?

A

Route object

takes the path (url path)

renders component based on path

Ex. /Products will render Products component

94
Q

What is the Switch object?

A

import { Route, Switch } from “react-router-dom”;

will render first route that matches path

NOTE

order routes from most specific to general

95
Q

What are Single Page Applications (SPAs) ?

Hint: localhost (HTML page), bundle (combined all JS code)

A

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
Q

How do we convert our React app into a single page application?

A

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
Q

What is a Route component?

A

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
Q

How can we set additional props when using a route in React?

A

use render ( ) attribute vs. component attribute

set render attribute to arrow fn

Ex. () => additionalPropParams=”” >

arrow fn returns Products component w/ props

99
Q

What’s the problem here?

Hint: other props missing (history, match, etc.)

A

Solution:

Pass props in arrow fn as args

use spread operator and jsx will add props to component

100
Q

How do we define route parameters in React?

A

/:param

Match prop contains route params

can read route params passed to component from match

{this.props.match.params.id}

101
Q

How do we stop our pages from doing full page renders?

Hint: convert to single page application?

A

replace with

replace href= with ‘to’

import { Link } from ‘react-router-dom’;

102
Q

How do we make parameters optional?

A

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
Q

What are query strings?

A

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
Q

How do we extract query string params from a route?

A

npm i query-string

queryString.parse(location.search)

location.search = where query string params are stored

105
Q

How can we read route parameters passed to a component?

A

object adds history, location, match props

match props stores route parameters

{this.props.match.params.id }

106
Q

How do we re-direct a user to a new page or a page not found?

A

import { Route, Switch, Redirect } from “react-router-dom”;

107
Q

Where are route parameters vs. query string parameters?

A

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
Q

How do we re-direct a user when they click a button or submit a form?

Hint: Programmatic re-navigation

A

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
Q

How do we implement nested routing?

A

Ex. We have a navigation bar in header, side navigation bar (second navigation)

component can be used anywhere!

110
Q

How do we extract query string parameters?

A

url/?queryStringParams

accessible in location.search field

const { destructureQueryString } = queryString.parse(location.search)

location is a prop inserted by Router into our component

111
Q

How do we add routing to our vidly application?

A

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
Q

What are we going to build in the forms section?

A

Almost every application needs some kind of form

Login Form

Registration Form

Add/Edit movies Form

Search Box

113
Q

How do we properly submit a form in React?

A

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
Q

How do we get the value of our input field in a form?

Hint: Refs solution

A

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
Q

How do we get data from an input field?

Hint: Controlled elements

A

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
Q

What is a controlled element?

Hint: input fields, headers, anchors

have their own state (data)

A

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
Q

What’s the problem with this code?

A

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
Q

How do we implement validation on our input field?

A

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
Q

What is a basic implementation of validation in forms?

A

use npm joi-browser for actual validation

120
Q

How do we validate forms using joi in React?

A

npm i joi-browser

121
Q

How can we refactor this code?

Hint: Extract re-usable validation logic

A

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
Q

How can we refactor the render method?

A

submit button is re-usable

extract into form.jsx

input field is re-usable

extract into form.jsx

123
Q

How do we refactor this?

A

use the rest operator and spread operator

can automatically set any additional attributes in our props

124
Q

How do we make this method generic?

Hint: change from dot notation to bracket notation

A

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
Q

How do we add a movie form to our app?

A
126
Q

How do we add a search input to our App?

A
127
Q

How can we use a fake backend in our APP?

A

JSON Placeholder

provides endpoints (REST) for us to access

can send HTTP request (GET, POST, PUT)

128
Q

What is React only?

A

A lightweight 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
Q

How can we make HTTP requests in our React applications?

Hint: Axios

A

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
Q

Why do we need promises?

Hint: axios.get (‘api/endpoint’) returns promise

A

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
Q

How do we get the result of our async operation (HTTP GET request)?

A
132
Q

How do we call Server to populate posts in our React app?

Hint: HTTP GET request

A

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
Q

How do we perform and HTTP POST request?

Hint: axios.post (apiEndpoint, resource)

A
134
Q

How do we execute a POST request using axios?

A
135
Q

How do we execute a DELETE request?

Hint: axios.delete(endPoint/resourceID)

A
136
Q

What are pessimistic updates?

Hint: GET, POST, DELETE

A

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
Q

What are optimistic updates?

A

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
Q

What types of errors do we have in our React Apps?

Hint: Expected vs. Unexpected

A

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
Q

How can we differentiate between whether the error is expected or unexpected?

A

exception object

ex. request
ex. response

if server down, etc. won’t get a response (field will be null)

140
Q

How do we initialize a component?

A

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
Q

What is axios.interceptor?

A

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
Q

How do we handle unexpected errors?

A

with interceptor

handle unexpected errors globally

143
Q

When do we need try catch blocks?

A

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
Q

What’s the problem with this code?

Hint: it’s not re-usable, it is polluting App code

A

extract into HTTP module

can import into new projects, etc

hide axios behind http module

145
Q

How do we display Toast notifcations?

Hint: npm i react-toastify

A

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
Q

What is Sentry?

Hint: logging as a service

A

$npm install –save @sentry/react @sentry/tracing

147
Q

Why does Mosh like Sentry?

Hint: can log, view breadcrumbs, assign to devs on team, etc.

A

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
Q

How do we delete a movie from React App using our Node backend?

A
149
Q

How can we fill our form with data from our backend (node/express/mongoDb)?

A

refactor to populate genres() and populate movies ( )

150
Q

How can we refactor this?

A

code is telling a story

when looking at componentDidMount ( )

can tell two things should happen (populating genre, populating movie)

151
Q

How can we refactor this code?

A
152
Q

What are we learning in the Authentication and Authorization sections?

A

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
Q

How do we register a user?

A

create a userService.js

import userService in registerForm.jsx

154
Q

How do we handle errors in the registration form?

A

wrap call to server in a try-catch block

155
Q

How do we log in a user in our React App?

Hint: call the auth endpoint (node/express/mongoDb)

A

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
Q

How do we handle errors in Login form?

A
157
Q

Where do we store JWT on browser?

A

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
Q

What is a problem React developers face?

A

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
Q

How do we log a user in upon registration?

A

get the response from server

header(‘x-auth-token)

store x-auth-token in local storage after registering user

160
Q

How should we organize our import statements?

A

organize:

third party library

components

css files

161
Q

How do we get the current user?

A

during App.componentDidMount ( )

get JWT from local storage

decode JWT

Set User to App.state

162
Q

How can we render the login / register links in our nav bar conditionally?

A

set user in App.state

pass user object in props to NavBar

163
Q

What’s the problem with this code?

Hint:

A

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
Q

How do we implement Logout?

A
165
Q

How do we refactor our login, logout, etc.?

Hint: create authService.js to handle JWT

A
166
Q

How do we call protected API endpoints?

A

get jwt from local storage

send in request header w/ axios

167
Q

What is a common and dangerous design issue?

A

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
Q

How do we get rid of this bi-directional dependency?

A

reverse the dependency

have auth service give jwt to http module

vs.

http module requesting authService to give jwt

169
Q

How do we hide elements from the UI if a user is not given permissions?

A

Example

Hiding a button on the movies page

Solution

Pass user obj as a prop to movies component

conditionally render HTML content based on JSX expression

Hint

Inside a route, pass additional props

render={props =>

170
Q

How do we protect routes from a user without a valid jwt?

A

Make details page accessible only if logged in with jwt

App.js

171
Q

How do we refactor this code?

A

Create ProtectedRoute.jsx

(common component)

Have ProtectedRoute render a Route component

172
Q

How do we create a protected Route?

A

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
Q

How do we re-direct a user to the previous page they were on before reaching a protected route and being required to login?

A

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
Q

How do we hide the delete button in our movies table if a user isn’t logged in?

A

use authService to getUser

175
Q

What are we learning in deployment?

A

Environment variables

setting development, test, production level environment variables

Production Builds

optimize code for delivery to any servers

Deploy to Heroku

cloud service

176
Q

What environment does every application go through?

Hint: Development, Test, Production

A

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
Q

What is process.env?

A

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
Q

What happens to expressions that reference environment variables at build time?

A

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
Q

What does npm start give us?

A

A development 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
Q

What does npm run build give us?

A

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
Q

What is mLab?

A

Used to deploy MongoDb in the cloud

182
Q

How do we deploy our backend to heroku?

A

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
Q

What are higher order components?

A

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
Q

What are hooks?

A

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
Q

What is the useState ( ) hook?

A

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
Q

What is the problem with lifecycle methods in class components?

A

logic gets spread around

some logic in componentDidMount()

other logic in componentDidUpdate()

187
Q

What is the useEffect hook?

A

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
Q

What is the benefit of a custom hook?

A

can extract common logic and pass to multiple components

189
Q

How can we fetch data with a hook?

A
190
Q

How do we pass objects down via context in class components?

A

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
Q

How do we set the context type in a class component?

A

can use context to make decisions

set static property (static contextType = UserContext)

192
Q

How do we use context in functional components?

A

useContext hook in React

pass context as argument

don’t have a context consumer component underneath

makes hierarchy cleaner

193
Q

What is difference between context in functional components vs. class components?

A

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
Q

How do we pass down a method in our context tree to update context?

A

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
Q
A