How to include custom error payload in hapi Boom

Issue #969 Hapi.js, commonly referred to as Hapi, is an open-source, back-end web application framework for building and deploying web applications and APIs in Node.js In Hapi.js, you can use the Boom module to create and return error responses in a standardized way. Boom provides a set of functions to generate HTTP error objects with consistent properties, making it easier to handle errors and communicate them to clients Read Error transformation...

January 31, 2024 路 1 min 路 Khoa Pham

How to use useCallback in React

Issue #966 The use of useCallback and useMemo in React hooks is an adaptation to address certain limitations inherent in the functional programming style adopted by React. In JavaScript, every entity, whether it鈥檚 a function, variable, or any other type, gets created in memory when the code within a function鈥檚 scope is executed. This poses a challenge for React鈥檚 rendering logic, which determines the need for re-rendering based on changes in input props and context....

January 26, 2024 路 2 min 路 Khoa Pham

How to extend class in Javascript

Issue #965 In JavaScript, classes are a template for creating objects. They encapsulate data with code to work on that data. ES6 introduced a class syntax to the JavaScript language to create classes in a way that鈥檚 similar to other object-oriented programming languages like Java or C#. Extending classes is also a feature of ES6, which allows you to create a new class from an existing class. This is done through the extends keyword....

January 25, 2024 路 4 min 路 Khoa Pham

How to use export all and export default in Javascript

Issue #964 In JavaScript, particularly in modules used in frameworks like React, export statements are used to expose code鈥攕uch as functions, classes, or constants鈥攆rom one module so that they can be imported and reused in other modules. export * The export * syntax is used to re-export all exportable members from the imported module. It鈥檚 a way to aggregate exports from several modules into a single module. For example, let鈥檚 say we have a couple of modules, each exporting some components:...

January 25, 2024 路 2 min 路 Khoa Pham

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)) return [] } 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 } 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 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 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( }} 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( }} 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 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