How to use dynamic route in react router 5

Issue #658 Declare routes, use exact to match exact path as finding route is from top to bottom. For dynamic route, I find that we need to use render and pass the props manually. Declare Router as the rooter with Header, Content and Footer. Inside Content there is the Switch, so header and footer stay the same across pages import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' function Content() { return ( <Switch> <Route exact path="/about"> <About /> </Route> <Route exact path="/"> <Home /> </Route> <Route path='/book/:id' render={(props) => { return ( <BookDetail {....

June 3, 2020 · 1 min · 195 words · Khoa

How to use folder as local npm package

Issue #657 Add library folder src/library src library res.js screens Home index.js package.json Declare package.json in library folder { "name": "library", "version": "0.0.1" } Declare library as dependency in root package.json "dependencies": { "library": "file:src/library" }, Now import like normal, for example in src/screens/Home/index.js import res from 'library/res'

June 1, 2020 · 1 min · 48 words · Khoa

How to scroll to element in React

Issue #648 In a similar fashion to plain old javascript, note that href needs to have valid hash tag, like #features <a href='#features' onClick={() => { const options = { behavior: 'smooth' } document.getElementById('features-section').scrollIntoView(options) }} > Features </a> Updated at 2020-05-06 08:36:21

May 6, 2020 · 1 min · 42 words · Khoa

How to make simple filter menu in css

Issue #643 Use material icons <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> div#filter-container { display: flex; align-items: center; justify-content: center; margin-top: 10%; height: 60px; } div#filter-items { display: inline-flex; background-color: #fff; box-shadow: 0 0 1px 0 rgba(52, 46, 173, 0.25), 0 15px 30px 0 rgba(52, 46, 173, 0.1); border-radius: 12px; overflow: hidden; padding: 10px; } a.filter-item { display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100px; text-decoration: none; padding: 10px; } a.filter-item:hover { background-color: rgb(239, 240, 241); border-radius: 10px; } a....

April 27, 2020 · 1 min · 179 words · Khoa

How to add independent page in hexo

Issue #641 Create a new page hexo new page mydemo Remove index.md and create index.html, you can reference external css and js in this index.html. Hexo has hexo new page mydemo --slug but it does not support page hierarchy Specify no layout so it is independent page. --- layout: false ---

April 26, 2020 · 1 min · 51 words · Khoa

How to use async function as parameter in TypeScript

Issue #640 async function useCache( collectionName: string, key: string, response: functions.Response<any>, fetch: () => Promise<any> ): Promise<any> { const existing = await db.collection(collectionName).doc(key).get() if (existing.exists) { response.send(existing.data()) return } const object = await fetch() const json = Object.assign({}, object) await db.collection(collectionName).doc(key).set(json) response.send(object) } useCache( "books", key, response, async () => { const service = new Service() return await service.doSomething(key) } )

April 21, 2020 · 1 min · 61 words · Khoa

How to get ISO string from date in Javascript

Issue #552 type Components = { day: number, month: number, year: number } export default class DateFormatter { // 2018-11-11T00:00:00 static ISOStringWithoutTimeZone = (date: Date): string => { const components = DateFormatter.format(DateFormatter.components(date)) return `${components.year}-${components.month}-${components.day}T00:00:00` } static format = (components: Components) => { return { day: `${components.day}`.padStart(2, '0'), month: `${components.month}`.padStart(2, '0'), year: components.year } } static components = (date: Date): Components => { return { day: date.getDate(), month: date.getMonth() + 1, year: date....

December 22, 2019 · 1 min · 78 words · Khoa

How to apply translations to Localizable.strings

Issue #492 Suppose we have a base Localizable.strings "open" = "Open"; "closed" = "Closed"; After sending that file for translations, we get translated versions. "open" = "Åpen"; "closed" = "Stengt"; Searching and copy pasting these to our Localizable.strings is tedious and time consuming. We can write a script to apply that. Remember that we need to be aware of smart and dump quotes .replace(/\"/g, '') .replace(/\"/g, '') const fs = require('fs') const originalFile = 'MyApp/Resources/nb....

November 5, 2019 · 2 min · 239 words · Khoa

How to use react-native link and CocoaPods

Issue #476 React Native comes with a default React library, and most CocoaPods libraries for React Native has React as a dependency pod, which causes the conflict https://github.com/react-native-community/react-native-svg/issues/621 https://stackoverflow.com/questions/45296994/difference-between-react-native-link-and-cocoapods https://github.com/onmyway133/notes/issues/486 https://github.com/facebook/react-native/pull/23563

October 29, 2019 · 1 min · 31 words · Khoa

How to notarize electron app

Issue #430 Use electron builder npm install electron-builder@latest --save-dev Prefer electron-builder over electron-packager Configuration https://www.electron.build/configuration/configuration package.json { "name": "icon_generator", "version": "1.3.0", "description": "A macOS app to generate app icons", "main": "babel/main.js", "repository": "https://github.com/onmyway133/IconGenerator", "author": "Khoa Pham", "license": "MIT", "scripts": { "start": "npm run babel && electron .", "babel": "babel ./src --out-dir ./babel --copy-files", "dist": "npm run babel && electron-builder" }, "build": { "appId": "com.onmyway133.IconGenerator", "buildVersion": "20", "productName": "Icon Generator", "icon": "....

September 26, 2019 · 2 min · 314 words · Khoa

How to use custom domain for GitHub pages

Issue #423 In DNS settings Add 4 A records A @ 185.199.110.153 A @ 185.199.111.153 A @ 185.199.108.153 A @ 185.199.109.153 and 1 CNAME record CNAME www learntalks.github.io In GitHub Select custom domain and type learntalks.com In source public/CNAME learntalks.com

September 17, 2019 · 1 min · 40 words · Khoa

How to replace all occurrences of a string in Javascript

Issue #420 const normalized = string .replace(/\//g, '') .replace(/\"/g, '') .replace(/\(/g, '') .replace(/\)/g, '')

September 16, 2019 · 1 min · 14 words · Khoa

How to read and write file using fs in node

Issue #419 function write(json) { const data = JSON.stringify(json) const year = json.date.getFullYear() const directory = `collected/${slugify(className)}/${year}` fs.mkdirSync(directory, { recursive: true }) fs.writeFileSync( `${directory}/${slugify(studentName)}`, data, { overwrite: true } ) } async function readAll() { const classes = fs.readdirSync('classes') classes.forEach((class) => { const years = fs.readdirSync(`classes/${class}`) years.forEach((year) => { const students = fs.readdirSync(`classes/${class}/${year}`) students.forEach((student) => { const data = fs.readFileSync(`classes/${class}/${year}/${student}) const json = JSON.parse(data) }) }) }) }

September 16, 2019 · 1 min · 68 words · Khoa

How to get videos from vimeo in node

Issue #418 Code Path for user users/nsspain/videos Path for showcase https://developer.vimeo.com/api/reference/albums#get_album Path for Channels, Groups and Portfolios const Vimeo = require('vimeo').Vimeo const vimeoClient = new Vimeo(vimeoClientId, vimeoClientSecret, vimeoAccessToken) async getVideos(path) { const options = { path: `channels/staffpicks/videos`, query: { page: 1, per_page: 100, fields: 'uri,name,description,created_time,pictures' } } return new Promise((resolve, reject) => { try { vimeoClient.request(options, (error, body, status_code, headers) => { if (isValid(body)) { resolve(body) } else { throw error } }) } catch (e) { reject(e) console....

September 16, 2019 · 2 min · 228 words · Khoa

How to get videos from youtube in node

Issue #417 class Youtube { async getVideos(playlistId, pageToken) { const options = { key: clientKey, part: 'id,contentDetails,snippet', playlistId: playlistId, maxResult: 100, pageToken } return new Promise((resolve, reject) => { try { youtube.playlistItems.list(options, (error, result) => { if (isValid(result)) { resolve(result) } else { throw error } }) } catch (e) { reject(e) } }) } } Response look like { "kind": "youtube#playlistItemListResponse", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/ZNTrH71d3sV6gR6BWPeamXI1HhE\"", "nextPageToken": "CAUQAA", "pageInfo": { "totalResults": 32, "resultsPerPage": 5 }, "items": [ { "kind": "youtube#playlistItem", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/pt-bElhU3f7Q6c1Wc0URk9GJN-w\"", "id": "UExDbDVOTTRxRDN1X0w4ZEpyV1liTEI4RmNVYW9BSERGdC4yODlGNEE0NkRGMEEzMEQy", "snippet": { "publishedAt": "2019-04-11T06:09:26....

September 13, 2019 · 1 min · 209 words · Khoa

How to convert callback to Promise in Javascript

Issue #416 // @flow const toPromise = (f: (any) => void) => { return new Promise<any>((resolve, reject) => { try { f((result) => { resolve(result) }) } catch (e) { reject(e) } }) } const videos = await toPromise(callback) If a function accepts many parameters, we need to curry https://onmyway133.github.io/blog/Curry-in-Swift-and-Javascript/ function curry2(f) { return (p1) => { return (p2) => { return f(p1, p2) } } } const callback = curry2(aFunctionThatAcceptsOptionsAndCallback)(options) const items = await toPromise(callback)

September 13, 2019 · 1 min · 76 words · Khoa

How to fix electron issues

Issue #415 Electron require() is not defined https://stackoverflow.com/questions/44391448/electron-require-is-not-defined function createWindow () { win = new BrowserWindow({ title: 'MyApp', width: 600, height: 500, resizable: false, icon: __dirname + '/Icon/Icon.icns', webPreferences: { nodeIntegration: true } }) } DevTools was disconnected from the page npm install babel-cli@latest --save-dev npm install react@16.2.0 win.openDevTools() This leads to Cannot find module 'react/lib/ReactComponentTreeHook' If we’re using binary, then rebuild, it is the problem that cause devTools not work...

September 12, 2019 · 1 min · 152 words · Khoa

How to make simple traffic simulation in Javascript

Issue #400 Use prototype.js for inheritance Use enchant.js for 2d game logic Code https://github.com/onmyway133/traffic_simulator

September 5, 2019 · 1 min · 14 words · Khoa

How to make collaborative drawing canvas with socketio and node

Issue #399 Client Use https://github.com/facebook/create-react-app App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Main from './Main' class App extends Component { render() { return <Main /> } } export default App; Main.js // @flow import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import Manager from '....

September 5, 2019 · 2 min · 334 words · Khoa

How to generate changelog for GitHub releases with rxjs and node

Issue #398 How to Use https://github.com/onmyway133/github-changelogs-maker Generate personal access token https://github.com/settings/tokens Technical Dependencies const Rx = require('rxjs/Rx') const Fetch = require('node-fetch') const Minimist = require('minimist') const Fs = require('fs') Use GraphQL makeOptions(query, token) { return { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `bearer ${token}` }, body: JSON.stringify({ query: ` query { repository(owner: "${this.owner}", name: "${this.repo}") { ${query} } } ` }) } } Use orderBy fetchPRsAndIssues(dates) { const query = ` pullRequests(last: 100, orderBy: {field: UPDATED_AT, direction: ASC}) { edges { node { title merged mergedAt url author { login url } } } } issues(last: 100, orderBy: {field: UPDATED_AT, direction: ASC}) { edges { node { title closed updatedAt url } } } } }

September 5, 2019 · 1 min · 117 words · Khoa