React 39

How to use React Query useQuery with debounce

Issue #979

When dealing with user input, such as in an autocomplete component, it’s common to implement debouncing to reduce the number of API calls and improve the user experience.

React Query’s useQuery hook makes it easy to manage the …

How to use React Custom Hooks as the View Model pattern

Issue #975

When building a React application, separating the logic and state management from the UI can make your code easier to manage, test, and reuse. This is where the view model pattern comes in handy. By using a custom hook as a view model, you …

How to use act vs waitFor using React Testing Library

Issue #971

When testing React components, dealing with tasks that happen at different times is super important to make sure your tests give reliable results. React Testing Library gives you two important tools for dealing with these situations: act …

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 …

How to read image paste from clipboard in React

Issue #968

Are you looking to grab images directly from your clipboard with a button click on your web page? The Async Clipboard API makes this quite easy and efficient. Let’s break it down into simpler steps:

Requesting Permission

The first …

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’s a function, variable, or any …

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 = …

How to get Supabase user token from server API

Issue #947

Sometimes Row Level Security is not enough and we want to do all logic server side, then we need a way for the server to get hold onto current user token.

Send JWT token in Authorization header

From client, we can get session from supabase …

How to mirror auth.users on Supabase

Issue #946

For security purposes, the auth schema is not exposed on the auto-generated API. We can make a profiles table in public namespace and mirror data from auth.users when user signs up.

I need id, username and raw_user_metadata so I will …

How to use Supabase auth with React Context

Issue #942

Expose supabase with createClient

useSupabase.ts

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = process.env.SUPABASE_URL
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY

export const supabase = …

How to create React app with Parcel

Issue #941

In this tutorial we will be creating a React app with Parcel 2 with Typescript and Tailwind

Install the following dependencies. Parcel supports TypeScript out of the box without any additional configuration.

npm install --save-dev parcel …

How to make reusable Button component in React

Issue #936

From https://github.com/antonioerdeljac/next13-spotify

import { forwardRef } from "react";
import { twMerge } from "tailwind-merge";

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement …

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 …

How to fallback img in React

Issue #804

<img 
    src={user.avatarUrl} 
    onError={(e) => {
        e.target.onerror = null; 
        e.target.src = "/images/default.png"
    }}
/>

Extract to React Component

interface Props {
    src: string
    className: …

How to use videojs in React

Issue #803

import React from 'react';
import videojs from 'video.js'
import 'video.js/dist/video-js.css';

export default class VideoPlayer extends React.Component {
    createPlayer() {
        // instantiate Video.js …

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"
} …

How to use default system fonts in React apps

Issue #700

In index.css

body {
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica …

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 ( …

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. …

How to go back to home in React

Issue #665

Usually in header we have logo that takes user back to the home page

// index.js
import {
    BrowserRouter as Router,
    Switch,
    Route,
    Link
} from 'react-router-dom'

<Router>
    <Switch>
        <Route …

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 …

How to style video js

Issue #663

/** @jsx jsx */
import { css, jsx } from '@emotion/core'
import React from 'react';
import videojs from 'video.js'

export default class VideoPlayer extends React.Component {
    componentDidMount() {
        // …

How to use setState in React

Issue #662

Use spread operator

import React, { Component, useState, useEffect } from 'react';

const [state, setState] = useState({
        message: '',
        chats: [],
        sending: false
})

setState(prevState => ({ …

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 …

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 …

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
} …

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 …

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" …

How to update multiple state properties with React hooks

Issue #655

Declare state and setState

export default function Showcase(props) {
    const factory = props.factory
    const [state, setState] = useState(
        {
            factory,
            selectedFilter: { name: '' }
        }
    ) …

How to make white label React app

Issue #654

Use shelljs to execute shell commands, and fs to read and write. In public/index.html specify some placeholder and we will replace those in our script

const fs = require('fs');
const shell = require('shelljs')

let …

How to make white label React app for landing pages

Issue #654

A good landing page is one of the most crucial part of a successful launch. Recently I started creating landing pages for my apps, I was lazy that I ended creating a white label React app as a landing template and then write a script to …

How to show lightbox in React

Issue #653

Use https://github.com/biati-digital/glightbox

Configure css. Specify class='glightbox for html elements

<link rel="stylesheet" href="css/blueimp-gallery.min.css" />

Install package

npm install glightbox
import …

How to animate on scroll in React

Issue #652

Use https://github.com/michalsnik/aos

Add link to head

<head>
    <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
</head>

Jus before closing body tag

<script src= …

How to conditionally apply css in emotion js

Issue #649

Check flag then define css

const Picture = (feature) => {
    const shadowCss = feature.shadow ? css`
        border-radius: 5px;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    ` : css`` …

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'
        } …

How to use emotion for inline css in React

Issue #647

emotion can be used in framework agnostic or with React. To use with React, follow https://emotion.sh/docs/introduction#react

npm i @emotion/core

Note that you must have /** @jsx jsx */ at the top of the file, and the unused jsx in import …

How to use React JSX with Babel in Electron

Issue #352

For a normal electron app created with npm init, we can use all features of ES6, but not the JSX syntax for React. We can use just Babel to transpile JSX, as used in IconGenerator

.babelrc

{
  "plugins": [ …

How to catch error in ApolloClient

Issue #192

Read https://www.apollographql.com/docs/react/features/error-handling How to catch actual error https://github.com/apollographql/apollo-client/issues/4016 🤔

import { Observable } from 'apollo-link'
import ApolloClient from …

How to handle file picker in React

Issue #190

render() {
  <Button color="inherit" onClick={this.onImagePress} >Image</Button>
  <input ref="fileInput" type="file" id="myFile" multiple accept="image/*" style={{display: …