Please enable JavaScript.
Coggle requires JavaScript to display documents.
React.JS (Create a blank Project: Use create-react-app (npx = NPM package…
React.JS
Create a blank Project:
Use create-react-app
npx = NPM package Runner
Firstly Install Nodejs
npx create-react-app my-app
cd my-app
npm start
React.js & JavaScript
React Component
1.Extends Component
2.Must implement render()
3.Is a class or function
4.One components can contains many other components
class ProductComponent extends Component {
render
() {
return (<div className="...">
<h1>I like {this.props.product.name}</h1>
</div>)
}
}
JSX:
<h1>I like...</h1>
OR
<div className...></div>
JSX in short form:
<ProductComponent />
1 more item...
A bit different with HTML tag:
"className", not "class"
JSX with props:
<ProductComponent product={{name: "iphone", year: 2019}} />
What is component's data ?
props and state
2 more items...
Basic components
<button></button>
1.className
2.onClick={}
3.type => "submit"
4.disabled={false}
<input.../> props:
1.name
2.value
3.onChange={...}
4.type
5.placeholder
2 more items...
Form
class SignUpForm extends Component {
render() {return <form onSubmit={...}></form>}
}
1 more item...
HOC - Higher-Order Component = Nested functions
import {x} from '...';
export const withX = Component => props => (
<div><Component {...props} x = {x}></div>
);
How to call function "withX" ?
class ComponentA {...}
export const withX(ComponentA);
How to call 2 HOC ?
export const withY(withX(ComponentA))
1 more item...
Do the same with withY:
export const withY =...
Lifecycle
When mounting:
1.constructor()
2.render() => required
3.componentDidMount()
When updating(props or state changed):
1.shouldComponentUpdate(nextProps, nextState)
2.render(), run if (1) = true
3.getSnapshotBeforeUpdate(prevProps, prevState)
4.componentDidUpdate(prevProps, prevState, snapshot)
componentDidUpdate:
must check:
if(prevProps.email !== this.props.email)...
to prevent "infinite loop"
1 more item...
In constructor:
1.Initialize state
2.Binding action:
this.handleClick = this. handleClick.bind(this)
Javascript ES6
Variables
Define a variable:
let x = 10 //inside a block
var y = 20 //inside a .js file
Compare value:
var x = 10
if(x == '10') {//true}
Compare value and type:
var x = 10
if(x === 10) {//Return true}
2 more items...
Alert a value:
alert(`x = ${x}`)
1 more item...
Object as "Dictionary":
var users = {
"111": {name:"...", email:"..."},
"222": {name:"...", email:"..."}
}
How to convert "Dictionary" to "Array" ?
Object.keys(dictUsers).map(key => ({...dictUsers[key]}));
Functions
Basic function:
function sum(x, y) {return x+y}
Arrow function:
const sum = (x, y) => {return....}
One-line function:
const sum = (x, y) => x+y
Arrow function with 1 param:
const square = x => x*x
Promise
Do something asynchronously
const doPromiseA = (param1, param2) => {return new Promise(....)}
1 more item...
Array, List
Array of objects:
let products = [{name: "iphone X", year: 2018}, {name: "iphone 6", year: 2016}]
Iterate an array:
products.forEach((product, index) => {
console.log(
Name = ${product.name}, index = ${index}
)
})
Map and update an existing array:
products = products.map((product, index) => { return ...})
1 more item...
Delete an item in list:
products = products.filter(product => {
return product.name !== "iphone 6"})
Find an item:
let foundProduct = products.find(product => {return product.year === 2018})
Add more items(mutable):
products.push({name: "iphone 5", year: 2015})
Add more items(un-mutable):
products.concat({name: "iphone 5", year: 2015})
1 more item...
Convert array to string:
strings = ["name='Hoang'", "age=30"]
let outputString = ", ".join(strings)
React Router & Firebase Auth
Firebase bought by Google,2014
A file for defining routes:
export const SIGN_UP = '/signup'
...
App Component changed
import { BrowserRouter as Router, Link } from 'react-router-dom';
const App = () => (<Router>
<div>
<Link to={SIGN_UP}>Sign up</Link>
<Link ....>
</div>
<Router>)
Route to Component Mapping
1 more item...
npm install react-router-dom
Open Firebase Console, create Project
Choose Web, not IOS, Android
You may see:
1.A <script> tag
2.A "var config"
Open Authentication
1.Choose tab "Sign-in Method"
2.Enable Email/Password signin
3.Facebook,Google,...
1 more item...
save secret info in .env file
REACT_APP_API_KEY=...
....
NODE_ENV === 'development'
1 more item...
Edit src/index.js:
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
import './index.css'
Open
http://localhost:3000
React + Foundation
npm install react-foundation --save
...
import Foundation from 'react-foundation';
Basic components
Buttons
Button:
1.color={Colors.SUCCESS}
2.isHollow => "outline button"
3.isExpanded
PRIMARY, SECONDARY, SUCCESS, ALERT, WARNING
Link:
1.size={Sizes.TINY}
2.color={Colors.PRIMARY}
3.isDisabled
4.isDropdown
TINY, SMALL, LARGE
ButtonGroup:
1.size
2.can contains many buttons
3.isExpanded
4.stackFor={Breakpoints.SMALL}
Switch:
1.input={{ type: InputTypes.RADIO, name: '...', defaultChecked: true }}/>
2.size
3.active={{ text: 'Yes' }} inactive={{ text: 'No' }
Menu
1.alignment={Alignments.RIGHT}
2.isExpanded
3.isVertical
4.isVertical
5.isSimple
6.isNested
7.iconsOnTop
Contains MenuItem
MenuItem can contains <a></a>
Inside <a> may contains Icon:
1.name="fi-list"
MenuItem:
isActive => has background color
isNested => Menu is inside a MenuItem
Pagination:
1.aria-label="Pagination"
2.isCentered
Contains:
PaginationPrevious
PaginationItem
<PaginationEllipsis/> => "..." sign
PaginationNext
Inside PaginationItem:
<a aria-label="Page 12">12</a>
PaginationItem
1.isCurrent
2.isDisabled
NodeJS + Postgres
PostgreSQL, since 1997
Install on Windows: using Installer
Search psql, click to run
on MacOS:
brew install postgresql
Start/stop service
brew services start postgresql
Default user/database = postgres/postgres
psql postgres
\conninfo
\c => Connect to a new DB
\l => List all databases
CREATE ROLE hoangnd WITH LOGIN PASSWORD 'mypasssword';
ALTER ROLE hoangnd CREATEDB;
Login again
psql -d postgres -U hoangnd
2 more items...
\du => for checking
\dt => Display all tables
\du => Display all users/roles
Nodejs & Express
Create a blank Nodejs:
npm init -y
Install express, pg for Nodejs:
npm i express pg
import some packages:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000
...
app.listen(port, () => {})
Use middleware for parsing JSON:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
Now connect Nodejs+Postgres
const {Pool} = require('pg').Pool
const connectionPool = Pool({user: 'hoangnd', host:,..database:..,password:.., port: 5432})
In database.js
Function for GET:
const getUsers = (req, res) => {
connectionPool.query("SELECT * FROM...", (error, results) =>
{response.status(200).json({....})})
}
...
module.exports = {getUsers,..}
...
In other file:
const db = require('./database.js')
app.get('/users', db.getUsers)
Query with params:
.query('SELECT * FROM users WHERE id = $1', [id], (error, results)...
INSERT INTO users (name, email) VALUES ($1, $2)', [name, email]...
'UPDATE users SET name = $1, email = $2 WHERE id = $3'
DELETE FROM users WHERE id = $1', [id]
Test Restful API(POST, GET, PUT, DELETE) using Postman
First simplest api:
app.get('/', (request, response) => {
response.json({...})
})
Deploy app to Heroku
React App
cd your_react_app_folder
npm install --save serve
Write some scripts in package.json:
"dev": "react-scripts start",
Production build:
"start": "serve -s build",
Login Heroku dashboard, create new App
Open "Deploy" tab, choose Github
Build and run in heroku:
"heroku-postbuild": "npm run build"
Name: Nguyen Duc Hoang
Youtube:
https://www.youtube.com/c/nguyenduchoang