Skip to content

Instantly share code, notes, and snippets.

View lwkchan's full-sized avatar

Laura Chan lwkchan

  • London, UK
View GitHub Profile
@lwkchan
lwkchan / logActiveElement.js
Created November 14, 2022 18:48
Logs active element in console when using tab key to navigate
document.body.addEventListener('keydown', function(e) {
if (e.which === 9) {
setTimeout(function() {
console.log(document.activeElement);
}, 100);
}
})

Testing with env vars

To test with different kinds of env vars in different unit tests we need to do the following.

  1. set up the vars on process.env.NODE_ENV
  2. run the test
  3. reset it

Step three is very important since process.env is a global variable, we want to make sure that when every test uses it, it returns what is expected.

@lwkchan
lwkchan / lazyLoad.js
Created October 11, 2019 09:29
Lazy loading images, with support for fallbacks for WebP and Intersection Observer
// Script for lazy loading off screen images and background css images
// Also checks for webp support and adds that image if provided
// <img class="lazy-load" data-src="path-to-image.jpeg" /> // images with no webp support
// <div class="lazy-load-bg" data-src="path-to-image.jpeg" [data-src-webp="path-to-image.webp"]></div> // css background images. data-src-webp is optional
// <picture> // <picture> with webp support:
// <source class="lazy-load" data-srcset="path-to-img.webp" type="image/webp">
// <source class="lazy-load" data-srcset="path-to-img.jpg" type="image/jpeg">
@lwkchan
lwkchan / dynamicInputBox.js
Last active June 7, 2019 17:15
Ensures that numpad keyboard shows but also shows commas when onBlur- Unfortunately does not work as expected on iOS
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const getNumericValueWithCommas = (value) => {
const separator = ",";
let output = "";
const numbersArray = value
.toString()

useLayoutEffect vs useEffect

useEffect

  • Fires after render (to virtual DOM) and browser paint
  • Will not block the browser from updating the screen as it runs asynchronously
  • Useful for side effects which are not concerned with DOM information

useLayoutEffect

  • Similar to componentDidMount/componentDidUpdate
  • Runs synchronously run after the DOM has been modified
@lwkchan
lwkchan / useCookie.js
Last active February 20, 2024 11:29
Simple React hook to get/set Cookies with 'universal-cookie' package 🍪
import {useState} from 'react';
import Cookies from 'universal-cookie';
const useCookie = (key, options = {}) => {
const cookies = new Cookies();
const [item, setItemValue] = useState(() => {
if (cookies.get(key)) {
return cookies.get(key);
}
return null;