REACT 1

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

node start in package json

"start": "node index.js"

error after axios call

.catch(error=>console.log(error))

after axios call chain

.then(response => { console.log(response.data); this.setState((state)=>{ state.wines=response.data; return state;

to make your own component class you must?

subclass React.Component class COMPONENTNAME

static analysis

testing code without actually running it. E.G., linting, typescript typing

To make a React component, you write a JSX element. What do you name it?

the same as your component class

all methods are written inside?

the state method

to change state

this.setState({})

to only change the state in the current file?

{this.xxxxxxxx.state.bind(this)}

what do you put between error and console.log

=>

virtual DOM

A JS object that is a virtual representation of the DOM. Any new view changes are first performed on the virtual DOM, which lives in memory and not on your screen. An efficient algorithm then determines the changes made to the virtual DOM to identify the changes that need to be made to the real DOM. It then determines the most effective way to make these changes and then applies only those changes to the real DOM. This guarantees a minimum update time to the real DOM, providing higher performance and a cleaner user experience all around.

JSX

A dialect of JavaScript that embeds raw HTML templates inside JavaScript code. JSX code by itself cannot be read by the browser; it must be transpiled into traditional JavaScript using tools like Babel and webpack.

What is node?

A javascript runtime for network applications like web servers. A JS enigne (V8) and a set of libraries that make it possible to write and execute network applications in Javascript.

express library

A minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. const app = express() : start an instance of express http server .get, .post, .delete ,etc(route, onReq callback) - method for handling requests to routes Middleware - functions between req and res that have accress to both objects. Most popular: logging, CORS, file compression, csrf pretection, cookie sessions

libuv

A multi-platform support library with a focus on asynchronous I/O. Some of the features of libuv are: Full-featured event loop Asynchronous file and file system operations Child processes File system events

Redux

A predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Most important features are single source of truth and enforcing of synchronous action handling. combineReducers({reducers}) - generates a function that calls your reducers with the slices of state selected according to their keys, and combining their results into a single object again. createStore(reducer) - self-explantory: creates store object

stateless component

A pure function that renders DOM object based solely on the properties (parameters) provided to it. No internal state, no lifecycle hooks

Component

A small, independent, reusable piece of UI. A function that returns a React element to be rendered to the DOM

Webpack

A static module bundler for modern JavaScript applications. It recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into one or more bundles.

async library

A utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Provides around 70 functions that include the usual 'functional' suspects (map, reduce, filter, each...) as well as some common patterns for asynchronous control flow (parallel, series, waterfall...). All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your asynchronous function -- a callback which expects an Error as its first argument -- and calling the callback once.

ReactDOMServer API

API for server-side rendering initial HTML. renderToString(element) - render initial HTML to string for faster first load, then Hydrate with client JS. renderToNodeStream(element) - same as above, but sends data as stream for faster transfer byte-by-byte

ReactDOM API

API providing top-level methods for DOM manipulation: render(element, containerRef) - Mount/update a react component to DOM hydrate(element, containerRef) - same as render, but for SSR HTML unmountComponentAtNode(containerRef) - remove component from DOM and clean up event listeners and state findDOMNode(component) - returns correspondingnative DOM element (throws exception for unmounted Component) createPortal(child, container) - a way of rendering an element outside of normal the native DOM hierarchy of the component, while preserving React DOM hierarchy. Good for Modals.

Flux pattern

An architectural pattern that enforces unidirectional data flow — its core purpose is to control derived data so that multiple components can interact with that data without risking pollution. SOLVES: vanilla and jQuery MVC problem of poorly defined data flow and lack of data integrity (storing state in the DOM). The Flux pattern is generic; it's not specific to React applications, nor is it required to build a React app. However, Flux is commonly used by React developers because React components are declarative — the rendered UI (View) is simply a function of state (Store data). action -> dispatcher -> store -> view the Store is the central authority for all data; any mutations to the data must occur within the store. Changes to the Store data are subsequently broadcast to subscribing Views via events. Views then update themselves based on the new state of received data. To request changes to any Store data, Actions may be fired. These Actions are controlled by a central Dispatcher; Actions may not occur simultaneously, ensuring that a Store only mutates data once per Action.

Webpack Entry

An entry point indicates which module webpack should use to begin building out its internal dependency graph. After entering the entry point, webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).

Controlled component

An input form element whose value is controlled by React. When a user enters data into a controlled component, a change event handler is triggered and your code decides whether the input is valid (by re-rendering with the updated value). If you do not re-render then the form element will remain unchanged.

Redux Action

An object that describes the outcome of an event. Payload of information that sends data from your application to your store. The only source of information for the store.

What is React?

An open-source JavaScript library created by Facebook for building UI components for web and mobile. It has no opinions on the other pieces of your technology stack and can be seamlessly integrated into any application.

context

Context lets components make data available to other components further down the tree without being passed through explictly as props. When a component defines some data onto its context, any of its descendants can access that data. That means any child further down in the component tree can access data from it, without being passed it as a property.

state

Data associated with a component that changes over time. The most important difference between state and props is that props are passed from a parent component, but state is managed by the component itself. A component cannot change its props, but it can change its state.

module

Discrete chunk of functionality. Each module has a smaller surface area than a full program, making verification, debugging, and testing trivial. Well-written modules provide solid abstractions and encapsulation boundaries, so that each module has a coherent design and a clear purpose within the overall application.

socket.io library

Enables real-time bidirectional event-based communication.

React API

Entry point for react library. Component - base class for React components when they are defined using ES6 classes. PureComponent - same as above, but implements shouldComponentUpdate() based on shallow comparison of state/props createReactElement(type, [props], [...children]) - method underlying JSX statements. Children - utilities object for dealing with the this.props.children opaque data structure (map, forEach, only, toArray). Fragment - Component that lets you return multiple elements in a render() method without creating an additional container DOM element createRef() - creates a ref that can be attached to React elements via the ref attribute.

Jest

Facebook's JS testing platform, includes testing snapshots of serialized component Assertions: expect(component) .toBe(value) .toHaveBeenCalled() .toHaveBeenCalledTimes(int) .toHaveBeenCalledWith(arg, arg, arg, ...) .toHaveProperty(key, val)

React 16 new features

Fragments - allows return of more than one top-level element from component. can be array of elements or <React.Fragment /> Error Boundaries and componentDidCatch - Prior to React v16.0, any error in any part of the UI would crash the whole application. Now a component with componentDidCatch method defined acts as boundary that conditionally renders based on error state createPortal(child, container) - a way of rendering an element outside of normal the native DOM hierarchy of the component, while preserving React DOM hierarchy. Good for Modals. stream support in serverside rendering (SSR) Context API - lets components make data available to other components further down the tree without being passed through explicitly as props.

JSX can either be either what? And uses what to distinguish the difference.

HTML-like, or component instances CAPS shows it's an instance of a class

how are class components written?

InUpperCamelCase

General component lifecycle

Initialization (mounting); State/props updates; Destruction (unmounting).

props

Inputs to a React component. Data passed down from a parent component to a child component. Props are readonly. They should not be modified in any way.

How does Node work?

It is single-threaded, and uses async callbacks and an event loop to perform tasks like fetching data or interacting with a DB

SPA

Single Page Application. An application that loads a single HTML page and all the necessary assets (such as JavaScript and CSS) required for the application to run. Any interactions with the page or subsequent pages do not require a round trip to the server which means the page is not reloaded.

Webpack loaders

Loaders enable webpack to process more than just JavaScript files. They give you the ability to leverage webpack's bundling capabilities for all kinds of files by converting them to valid modules that webpack can process. Loaders transform all types of files into modules that can be included in your application's dependency graph (and eventually a bundle). in other words, makes it so you can import/require non-js files

Stream

Objects that allow reading of data from the source and writing of data to the destination as a continuous process. There are four types of streams: read, write, duplex, transform

Major Benefits of React

Performance: rendering and virtual DOM. Unidirectional flow and functional programming. Developer experience: compile-time debugging, JSX, organization, devtools, community, ecosystem.

PureComponent

PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state.

how do you call al render method

React.DOM.render(< />, document.getElementById('app'))

when a react element is compiled it transforms into a what?

React.createElement() call

what goes at the bottom of app.js usually

ReactDOM.render( <MyComponentClass />, document.getElementById('app') );

write ReactDOM.render

ReactDOM.render( <Owl />, document.getElementById('app') );

Redux Reducer

Reducers specify how the application's state changes in response to actions sent to the store. Reducer is a function that takes current state and action as arguments, returns new state. thus, state remains immutable

ref

Refs provide a way to access DOM nodes or React elements created in the render method, in the few cases where you need to imperatively modify a child outside of the typical dataflow: Managing focus, text selection, or media playback; Triggering imperative animations; Integrating with third-party DOM libraries. Avoid using refs for anything that can be done declaratively.

Stub

Stubs are functions that simulate the behaviors of components/modules (i.e., dependencies). Used to provide expected data/functionality from a component/module that IS NOT being tested

Redux store

The object that holds application state and provides the following methods: .getState() - allows access to state .dispatch(action) - updates state; .subscribe(listener) - registers listeners

Webpack output

The output property tells webpack where to emit the bundles it creates and how to name these files, it defaults to ./dist. Basically, the entire app structure will get compiled into the folder that you specify in the output path.

Enzyme

Tool for testing React component output. Note that React provides its own testing utilities, but also recommends Enzyme and react-testing-library shallow(component) - constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components. mount(component) - Full DOM rendering is ideal for use cases where you have components that may interact with DOM APIs, or may require the full lifecycle in order to fully test the component (i.e., componentDidMount etc.) render() - used to render react components to static HTML and analyze the resulting HTML structure. find(selector) => wrapper (like jQuery) simulate(event)

diffing and reconciliation

When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one (diffing). When they are not equal, React will update the native DOM (reconciliation).

Webpack plugins

While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks. Plugins range from bundle optimization and minification all the way to defining environment-like variables. The plugin interface is extremely powerful and can be used to tackle a wide variety of tasks.

Uncontrolled component

Works like form elements do outside of React. When a user inputs data into a form field (an input box, dropdown, etc) the updated information is reflected without React needing to do anything. However, this also means that you can't force the field to have a certain value.

to make a component you do use what? And that is what?

a base class from the React library: React.Component a React.Component is a javascript class

what is a small reusable chunk of code that is usually used to render html

a component

every component must come from what?

a component class

steps to create context

at parent level, create MyContext with React.createContext() Create class MyProvider, set state inside the class, return MyContext.Provider (notice composition) MyProvider is equvalent of Redux store Wrap entire app in MyProvider Inside of component that needs access to context, create MyContext.Consumer component, and make its child a function that returns elements which can access the context!

axios call

axios({ method: 'get', url: 'http://myapi-profstream.herokuapp.com/api/f4b493/wines', responseType: 'json' })

where do you put instructions for a component

between the { }

methods are effectual

by returning elements

what is state?

change

what kind of component is this import React, { Component } from 'react'

component with life-cycle

component did mount with axios

componentDidMount(){ axios({ method: 'get', url: 'http://myapi-profstream.herokuapp.com/api/f4b493/wines', responseType: 'json' }).then(response => { console.log(response.data); this.setState((state)=>{ state.wines=response.data; return state; }) }).catch(error=>console.log(error)) }

method used with axios call

componentDidMount(){}

Update hooks

componentWillReceiveProps - (deprecated) getDerivedStateFromProps shouldComponentUpdate componentWillUpdate - (deprecated) render getSnapshotBeforeUpdate componentDidUpdate

Destruction hooks

componentWillUnmount

create div without jsx

const greatestDivEver = React.createElement( "div", null, "i am div" );

write a loop with a key

const people = ['Rowe', 'Prevost', 'Gare']; const peopleLis = people.map((person, i) => <li key={'person_' + i}>{people}</li> <li key={'person_' + i}>{person}</li> ));

Initialization hooks

constructor static getDerivedStateFromProps componentWillMount - (deprecated) render componentDidMount

flow in react

data flows downward. behavior flows upward

How do we change something?

event

concurrency

executing multiple function calls simultaneously, out of order, or partially. Can be achieved through multithreading or async

what do you put at the end of app.js?

export default App

you always name class same as what

file

this.state is???

immutable

render a component

import React from 'react'; import ReactDOM from 'react-dom'; class MyComponentClass extends React.Component { render() { return <h1>Hello world</h1>; } }; ReactDOM.render( <MyComponentClass />, document.getElementById('app') );

what kind of component is this import React from 'react'

stateless component

import config from "./config" does what?

it turns config into a variable

what do you have to add to jsx as an attribute usually for lists? When do you need this attribute?

keys The list-items have memory from one render to the next. For instance, when a to-do list renders, each item must "remember" whether it was checked off. The items shouldn't get amnesia when they render. A list's order might be shuffled. For instance, a list of search results might be shuffled from one render to the next.

Benefits of Node

low latency and high throughput- Non-blocking approach to serving requests means less time (and less memory) wasted waiting for I/O requests to resolve Built on V8, which is already super fast best for apps that are computationally simple, but high frequency of access

Chaining

mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.

whenever you make a component. That component inherits all the ________________________

methods of it's component class

update webpack run

npm run build

empty object

null

synthetic event

objects which act as a cross-browser wrapper around the browser's native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

REPL

read, evaluate, print, loop

never set state inside

render

render is a what? and return is a what

render = method return = statement

when you render a component you need what 2 things

render function with class in < /> and getElementById function with app id from the HTML file

to reset game?

set to 0


Ensembles d'études connexes

AICE INTERNATIONAL HISTORY... THE FIRST WORLD WAR 1914-1918 (1)

View Set

CTVA 100: Chapter 2: The Internet, Digital Media, and Media Convergence

View Set

Chapter 16: Financing Leverage and Capital Structure Policy

View Set

Sage Vantage MARK3303 Business Ethics Chapter 4 Test

View Set

Hematology Objectives Mod 4 and 5

View Set