Merge branches 'react' and 'react' of https://github.com/m-lamonaca/ProgrammingNotes into react

This commit is contained in:
Marcello Lamonaca 2021-03-18 22:10:56 +01:00
commit 5781f65858
3 changed files with 314 additions and 63 deletions

View file

@ -30,9 +30,9 @@
### Naming Conventions ### Naming Conventions
Elements | Case | Elements | Case |
----------|----------- | -------- | --------- |
variable | camelCase | variable | camelCase |
### Modern Mode ### Modern Mode
@ -225,82 +225,82 @@ Number("A") == NaN; //false ?!?
## Operators ## Operators
Operator | Operation | Operator | Operation |
---------------|---------------- | ------------ | --------------- |
`(...)` | grouping | `(...)` | grouping |
a`.`b | member access | a`.`b | member access |
`new` a(...) | object creation | `new` a(...) | object creation |
a `in` b | membership | a `in` b | membership |
### Mathemetical Operators ### Mathemetical Operators
Operator | Operation | Operator | Operation |
-----------|---------------- | -------- | -------------- |
a `+` b | addition | a `+` b | addition |
a `-` b | subtraction | a `-` b | subtraction |
a `*` b | multiplication | a `*` b | multiplication |
a `**` b | a^b | a `**` b | a^b |
a `/` b | division | a `/` b | division |
a `%` b | modulus | a `%` b | modulus |
### Unary Increment Operators ### Unary Increment Operators
Operator | Operation | Operator | Operation |
--------------|------------------ | ------------ | ----------------- |
`--`variable | prefix decrement | `--`variable | prefix decrement |
`++`variable | prefix incremente | `++`variable | prefix incremente |
variable`--` | postfiz decrement | variable`--` | postfiz decrement |
variable`++` | ostfix increment | variable`++` | ostfix increment |
### Logical Operators ### Logical Operators
Operator | Operation | Operator | Operation |
---------|---------------- | -------- | --------------- |
a `&&` b | logical **AND** | a `&&` b | logical **AND** |
a `||` b | logical **OR** | a `||` b | logical **OR** |
`!`a | logical **NOT** | `!`a | logical **NOT** |
### Comparison Operators ### Comparison Operators
Operator | Operation | Operator | Operation |
----------|-------------------- | --------- | ------------------- |
a `<` b | less than | a `<` b | less than |
a `<=` b | less or equal to | a `<=` b | less or equal to |
a `>` b | greater than | a `>` b | greater than |
a `>=` b | greater or equal to | a `>=` b | greater or equal to |
a `==` b | equaltity | a `==` b | equaltity |
a `!=` b | inequality | a `!=` b | inequality |
a `===` b | strict equality | a `===` b | strict equality |
a `!==` b | strict inequality | a `!==` b | strict inequality |
### Bitwise Logical Operators ### Bitwise Logical Operators
Operator | Operation | Operator | Operation |
-----------|----------------------------- | --------- | ---------------------------- |
a `&` b | bitwise AND | a `&` b | bitwise AND |
a `|` b | bitwise OR | a `|` b | bitwise OR |
a `^` b | bitwise XOR | a `^` b | bitwise XOR |
`~`a | bitwise NOT | `~`a | bitwise NOT |
a `<<` b | bitwise left shift | a `<<` b | bitwise left shift |
a `>>` b | bitwise rigth sigt | a `>>` b | bitwise rigth sigt |
a `>>>` b | bitwise unsigned rigth shift | a `>>>` b | bitwise unsigned rigth shift |
### Compound Operators ### Compound Operators
Operator | Operation | Operator | Operation |
------------|------------- | ---------- | ----------- |
a `+=` b | a = a + b | a `+=` b | a = a + b |
a `-=` b | a = a - b | a `-=` b | a = a - b |
a `*=` b | a = a * b | a `*=` b | a = a * b |
a `**=` b | a = a ** b | a `**=` b | a = a ** b |
a `/=` b | a = a / b | a `/=` b | a = a / b |
a `%=` b | a = a % b | a `%=` b | a = a % b |
a `<<=` b | a = a << b | a `<<=` b | a = a << b |
a `>>=` b | a = a >> b | a `>>=` b | a = a >> b |
a `>>>=` b | a = a >>> b | a `>>>=` b | a = a >>> b |
a `&=` b | a = a & b | a `&=` b | a = a & b |
a `^=` b | a = a ^ b | a `^=` b | a = a ^ b |
a `|=` b | a = a ! b | a `|=` b | a = a ! b |
## Decision Statements ## Decision Statements
@ -444,7 +444,7 @@ let merge = [ ...array1, ...attay2 ]; // merge the arrays contents in new array
// objects // objects
let obj = { prop1: value1, prop2: value2 }; let obj = { prop1: value1, prop2: value2 };
let clone = { ...obj }; let clone = { ...obj, prop: value }; // shallow copy, and update copy prop
let cloneAndAdd = { prop0: value0, ...obj, prop3: value3 }; let cloneAndAdd = { prop0: value0, ...obj, prop3: value3 };
// strings // strings
@ -559,7 +559,7 @@ let variable = value;
// object literal // object literal
let obj = { let obj = {
property: value, property: value,
variable, // instead of variable: variable to use the variable's value -> variable: value variable, // same as variable: variable
object: { object: {
... ...

View file

@ -0,0 +1,103 @@
# React Router
Popular routing library. Allows to specify a route through React components, declating which component is to be loaded for a given URL.
Key Components:
- **Router**: wrap the app entrypoint, usually `BrowserRouter`
- **Route**: "Load this component for this URL"
- **Link**: react-managed anchors that won't post back to the browser
## Routers
Router Types:
- *HashRouter*: `#route`, adds hashes to the URLs
- *BrowserRouter*: `/route`, uses HTML5 history API to provide clean URLs
- *MemoryRouter*: no URL
```js
// index.js
//other imports ...
import { BrowserRouter as Router } from "react-router-dom";
React.render(
<Router>
<App />
</Router>,
document.getElemendById("DomID");
)
```
```js
// Component.js
import { Route, Switch } from "react-router-dom";
<div>
{/* match route pattern exactly, all subroutes will be matched otherwise */}
<Route path="/" exact component={Component} />
<Route path="/route" component={Component} />
...
</div>
// only one child can match, similar to switch-case
<Switch>
<Route path="/" exact component={Component} />
<Route path="/route" component={Component} />
<Route component={PageNotFound} /> {/* mathes all non-existent URLs */}
</Switch>
```
### Redirectin
```js
import { Redirect } from "react-router-dom";
// redirects to another URL, should'nt be rendered on component mount but after an action
<Redirect to="/route" />
<Redirect from="/old-route" to="/new-route" />
{ condition && <Redirect to="/route" /> } // redirect if condition is true
// or redirect manipolating the history (alwais in props)
props.history.push("/new-route");
```
### URL Parameters & Query String
```js
// Given
<Route path="/route/:placeholder" component={Component} />
// URL: app.com/route/subroute?param=value
function Component(props) {
props.match.params.placeholder; // subroute
props.location.query; // { param: value }
props.location.pathname; // /route/subroute?param=value
}
```
### Propts
```js
import { Prompt } from "react-router-dom";
// displayes a prompt when the conditioni true
<Prompt when={condition} message="prompt message" />
```
## Link
Clicks on a link created with React-Router will be captured by ract an all the routing will happen client side.
```js
import { Link } from "react-router-dom";
// TARGET: <Route path="/route/:itemId" />
<Link to="/route/1">Text</Link>
// add styling attributes to the rendered element when it matches the current URL.
<NavLink to="/route" exact activeClassName="class">Text</NavLink>
<NavLink to="/route" activeStyle={ { cssProp: value } }>Text</NavLink>
```

148
JavaScript/React/Redux.md Normal file
View file

@ -0,0 +1,148 @@
# [Redux](https://redux.js.org/)
Redux is a pattern and library for managing and updating application state, using events called *actions*. It serves as a centralized store for state that needs to be used across the entire application, with rules ensuring that the state can only be updated in a predictable fashion.
## Actions, Store, Immutability & Reducers
### Actions & Action Creators
An **Action** is a plain JavaScript object that has a `type` field. An action object can have other fields with additional information about what happened.
By convention, that information is stored in a field called `payload`.
**Action Creators** are functions that creates and return an action object.
```js
function actionCreator(data)
{
return { type: ACTION_TYPE, payload: data } // action obj
}
```
### Store
The current Redux application state lives in an object called the **store**.
The store is created by passing in a reducer, and has a method called `getState` that returns the current state value.
The Redux store has a method called `dispatch`. The only way to update the state is to call `store.dispatch()` and pass in an action object.
The store will run its reducer function and save the new state value inside.
**Selectors** are functions that know how to extract specific pieces of information from a store state value.
```js
function configStore(initialState) {
return createStore(rootReducer, initialState);
}
replaceReducer(newReducer); // replace an existing reducer, useful for Hot Reload
store.dispatch(action); // trigger a state change based on an action
store.subscribe(listener);
store.getState(); // retireve current state
```
### Reducers
**Reducers** are functions that receives the current state and an action, decide how to update the state if necessary, and return the new state.
Reducers must **always** follow some specific rules:
- They should only calculate the new state value based on the `state` and `action` arguments
- They are not allowed to modify the existing `state`.
Instead, they must make *immutable updates*, by copying the existing `state` and making changes to the copied values.
- They must not do any asynchronous logic, calculate random values, or cause other "side effects"
```js
function reducer(state, action) {
switch(action.type){
case "ACTION_TYPE":
return { ...state, prop: value }; // return modified copy of state (using spread operator)
break;
default:
return state; // return unchanged state (NEEDED)
}
}
// combining reducers
import { combineReducers } from "redux";
const rootReducer = combineReducers({
entity: entityReducer
});
```
## [React-Redux](https://react-redux.js.org/)
### Container vs Presentational Components
Container Components:
- Focus on how thing work
- Aware of Redux
- Subscribe to Redux State
- Dispatch Redux actions
Presentaional Components:
- Focus on how things look
- Unaware of Redux
- Read data from props
- Invoke callbacks on props
### Provider Component & Connect
Used at the root component and wraps all the application.
```js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import App from './App'
const rootElement = document.getElementById('root')
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
)
```
```js
// Component.js
import { connect } from 'react-redux'
import { increment, decrement, reset } from './actionCreators'
// const Component = ...
// specifies which state is passed to the component (called on satte change)
const mapStateToProps = (state, ownProps /* optional */) => {
// structure of the props passsed to the component
return { propName: state.property }
}
// specifies the action passed to a component (the key is the name that the prop will have )
const mapDispatchToProps = { actionCreator: actionCreator }
// or
function mapDispathToProps(dispatch) {
return {
// wrap action creators
actionCreator: (args) => dispatch(actionCreator(args))
}
}
// or
function mapDispathToProps(dispatch) {
return {
actionCreator: bindActionCreators(actionCreator, dispatch),
actions: bindActionCreators(allActionCreators, dispatch)
};
}
// both args ar optional
// if mapDispatch is missing the dispatch function is added to the props
export default connect(mapStateToProps, mapDispatchToProps)(Component)
```