Skip to content

Instantly share code, notes, and snippets.

@codeAdrian
codeAdrian / React Protected Route
Last active August 23, 2019 07:54
React Protected Route Component - based on https://tylermcginnis.com/react-router-protected-routes-authentication/ and extended with redirect prop
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({
component: Component,
isAuthenticated,
redirectTo,
...rest
}) => (
<Route
@codeAdrian
codeAdrian / React Form HOC
Last active May 31, 2018 16:52
React HOC for forms that keeps track of input values and stores it in state dynamically, handles submit events
import React, { Component } from "react";
const WithForm = (FormFields, action) => {
return class Form extends Component {
handleOnChange = event => {
const inputTarget = event.currentTarget || event.srcElement;
const { title, value } = inputTarget;
this.setState(
{
[title]: value
const user = {
firstName: "John",
};
const userProxy = new Proxy(user, {});
console.log(userProxy.firstName); // John
userProxy.firstName = "Johnny";
const user = {
firstName: "John",
};
const getHandler = (obj, prop) => {
// get object attributes
if(prop in obj) {
return obj[prop];
}
const user = {
firstName: "John",
};
const getHandler = (obj, prop) => {
// get object attributes
if(prop in obj) {
return Reflect.get(obj, prop); // Use object's static method
}
/* UTILS */
const getFullName = (firstName, lastName, middleName) =>
[firstName, middleName, lastName].filter((n) => !!n).join(" ");
const getFormattedBalance = (locale, currency, value) => {
return new Intl.NumberFormat(locale, {
style: "currency",
currency
}).format(value);
/* UTILS */
const getFullName = (firstName, lastName, middleName) =>
[firstName, middleName, lastName].filter((n) => !!n).join(" ");
const getFormattedBalance = (locale, currency, value) => {
return new Intl.NumberFormat(locale, {
style: "currency",
currency
}).format(value);
};
/* PROXY */
const handleSet = (obj, prop, value) => {
if (prop === "content" && value.length > 0 && value.length < 255) {
const { content, lastUpdated, history = [] } = obj;
const historyUpdated = [...history, { content, lastUpdated }];
if (content && lastUpdated) {
Reflect.set(obj, "history", historyUpdated);
}
/* PROXY */
const handleGet = (obj, prop) => {
if (prop === "undo") {
const last = obj.history.pop();
if (!last) {
return;
}
interface User {
firstName: string;
middleName?: string;
lastName: string;
email: string;
balance: number;
currency: string;
locale: string;
}