How to debounce text input in React

Issue #953 Use debounce from lodash and useCallback to memoize debounce function import React, { useCallback } from "react" import debounce from "lodash/debounce" const SearchField = (props: Props) => { const callback = useCallback( debounce((value: string) => { props.setFilter({ ...props.filter, searchText: value, }) }), [] ) const handleChange = (value: string) => { callback(value) } return ( <div> <Input value={props.filter.searchText} placeholder="Search" variant="bordered" onValueChange={handleChange} /> </div> ) }

November 19, 2023 路 1 min 路 Khoa Pham

How to remove duplicates in Javascript array while keeping latest occurrence?

Issue #952 Use ES6 Map The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value. type Deal = { name: string, link: string } removeDuplicates = (array: Deal[]) => { const map = new Map() array.forEach((item) => map.set(item.link, item)) return [...map.values()] } We might need to update tsconfig....

November 17, 2023 路 1 min 路 Khoa Pham

How to dynamically build tailwind class names

Issue #950 Inspired by shadcn Combine tailwind-merge: Utility function to efficiently merge Tailwind CSS classes in JS without style conflicts. clsx: constructing className strings conditionally. import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }

November 4, 2023 路 1 min 路 Khoa Pham

How to handle route case sensitivity in Nextjs

Issue #933 By default, Nextjs route is case sensitive, so localhost:3000/About and localhost:3000/about are different routes. To make uppercase routes become lowercase routes, we can add a middleware.tsx file to the src so it is same level as pages import { NextResponse, NextRequest } from "next/server" const Middleware = (req: NextRequest) => { if (req.nextUrl.pathname === req.nextUrl.pathname.toLowerCase()) { return NextResponse.next() } return NextResponse.redirect( new URL(req.nextUrl.origin + req.nextUrl.pathname.toLowerCase()) ) } export default Middleware

July 17, 2023 路 1 min 路 Khoa Pham

How to render markdown view with React

Issue #914 Use react-markdown to parse markdown content, react-syntax-highlighter to highlight code, and rehype-raw to parse raw html import ReactMarkdown from "react-markdown" import { Prism as SyntaxHighlighter } from "react-syntax-highlighter" import { oneDark } from "react-syntax-highlighter/dist/cjs/styles/prism" import rehypeRaw from "rehype-raw" type Props = { content: string } export default (props: Props) => { return ( <div className="markdown-body"> <ReactMarkdown children={props.content} rehypePlugins={[rehypeRaw]} components={{ code({ node, inline, className, children, ...props }) { const match = /language-(\w+)/....

June 6, 2023 路 1 min 路 Khoa Pham

How to use relative file module with Create React app

Issue #751 Declare data/package.json to make it into node module { "name": "data", "version": "0.1.0", "private": true, "homepage": ".", "main": "main.js" } Then in landing/package.json, use file { "name": "landing", "version": "0.1.0", "private": true, "homepage": ".", "dependencies": { "@emotion/core": "^10.0.28", "react": "^16.13.1", "react-dom": "^16.13.1", "react-image": "^2.4.0", "react-scripts": "3.4.1", "data": "file:../data" },

January 17, 2021 路 1 min 路 Khoa Pham

How to format ISO date string in Javascript

Issue #705 Supposed we have date in format ISO8601 and we want to get rid of T and millisecond and timezone Z const date = new Date() date.toDateString() // "Sat Dec 05 2020" date.toString() // "Sat Dec 05 2020 06:58:19 GMT+0100 (Central European Standard Time)" date.toISOString() // "2020-12-05T05:58:19.081Z" We can use toISOString, then split base on the dot . then remove character T date .toISOString() .split('.')[0] .replace('T', ' ')

December 5, 2020 路 1 min 路 Khoa Pham

How to make simple overlay container in React

Issue #699 Use term ZStack like in SwiftUI, we declare container as relative position. For now it uses only 2 items from props.children but can be tweaked to support mutiple class App extends React.Component { render() { return ( <ZStack> <Header /> <div css={css` padding-top: 50px; `}> <Showcase factory={factory} /> <Footer /> </div> </ZStack> ) } } /** @jsx jsx */ import React from 'react'; import { css, jsx } from '@emotion/core' export default function ZStack(props) { return ( <div css={css` position: relative; border: 1px solid red; `}> <div css={css` position: absolute; top: 0; left: 0; width: 100%; z-index: -1; `}> {props....

November 18, 2020 路 1 min 路 Khoa Pham

How to use useEffect in React hook

Issue #669 Specify params as array [year, id], not object {year, id} const { year, id } = props useEffect(() => { const loadData = async () => { try { } catch (error) { console.log(error) } } listenChats() }, [year, id]) } Hooks effect https://reactjs.org/docs/hooks-effect.html https://reactjs.org/docs/hooks-reference.html#useeffect By default, it runs both after the first render and after every update. This requirement is common enough that it is built into the useEffect Hook API....

June 17, 2020 路 1 min 路 Khoa Pham

How to format date in certain timezone with momentjs

Issue #664 Use moment-timezone https://momentjs.com/timezone/docs/ npm install moment-timezone // public/index.html <script src="moment.js"></script> <script src="moment-timezone-with-data.js"></script> Need to import from moment-timezone, not moment import moment from 'moment-timezone' moment(startAt).tz('America/Los_Angeles').format('MMMM Do YYYY')

June 13, 2020 路 1 min 路 Khoa Pham

How to handle evens in put with React

Issue #661 Use Bulma css <input class="input is-rounded" type="text" placeholder="Say something" value={value} onChange={(e) => { onValueChange(e.target.value) }} onKeyDown={(e) => { if (e.key === 'Enter') { onSend(e) } }} />

June 12, 2020 路 1 min 路 Khoa Pham

How to handle events for input with React

Issue #661 Use Bulma css <input class="input is-rounded" type="text" placeholder="Say something" value={value} onChange={(e) => { onValueChange(e.target.value) }} onKeyDown={(e) => { if (e.key === 'Enter') { onSend(e) } }} /> Updated at 2020-06-16 07:30:52

June 12, 2020 路 1 min 路 Khoa Pham

How to auto scroll to top in react router 5

Issue #659 Use useLocation https://reacttraining.com/react-router/web/guides/scroll-restoration import React, { useEffect } from 'react'; import { BrowserRouter as Router, Switch, Route, Link, useLocation, withRouter } from 'react-router-dom' function _ScrollToTop(props) { const { pathname } = useLocation(); useEffect(() => { window.scrollTo(0, 0); }, [pathname]); return props.children } const ScrollToTop = withRouter(_ScrollToTop) function App() { return ( <div> <Router> <ScrollToTop> <Header /> <Content /> <Footer /> </ScrollToTop> </Router> </div> ) } Updated at 2020-06-04 05:58:47

June 4, 2020 路 1 min 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham

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 路 Khoa Pham