Tuesday, August 18, 2020

Avoiding name clashes when using HoC in React

After watching Michael Jackson's video on HoC vs render props, I noticed that the problems in HoC he mentioned can be avoided, albeit the component authors have to make their component's property names be dynamic. The component's property name(s) have to be explicitly set.

To cut to the chase, here's one implementation: https://codesandbox.io/s/compassionate-curie-i1x7w

App.js
import React from "react";
import "./styles.css";
import { withMouse } from "./Mouse";
import { withCat } from "./Cat";

const withMouseProp = "mouse";
const withCatProp = "spawnDate";

class App extends React.Component {
  render() {
    const mouseProp = this.props[withMouseProp];
    const catProp = this.props[withCatProp];
    const { message } = this.props;

    return (
      <div className="App">
        <h1>{message}</h1>
        <h2>Start editing to see some magic happen!</h2>
        mouse is at {mouseProp.x} {mouseProp.y}
        <br />
        Cat spawn date: {catProp}
      </div>
    );
  }
}

export default withMouse(
  withCat(App, withCatProp, withMouseProp),
  withMouseProp
);
Mouse.js
import React from "react";

export function withMouse(Component, mousePropName) {
  return class extends React.Component {
    state = { x: 0, y: 0 };

    handleMouseMove = (event) =  {
      this.setState({
        x: event.clientX,
        y: event.clientY
      });
    };

    render() {
      const withPropName = { ...this.props, [mousePropName]: this.state };
      return (
        <div onMouseMove={this.handleMouseMove}>
          <Component {...withPropName} />
        </div>
      );
    }
  };
}
Cat.js
import React from "react";

export function withCat(Component, catPropName, mousePropName) {
  return class extends React.Component {
    state = { x: 0, y: 0 };

    componentDidUpdate(prevProps) {
      const mouse = this.props[mousePropName];
      if (
        mouse.x !== prevProps[mousePropName].x ||
        mouse.y !== prevProps[mousePropName].y
      ) {
        this.setState(mouse);
      }
    }

    render() {
      const mouse = this.props[mousePropName];
      const withPropName = {
        ...this.props,
        [catPropName]: new Date().toISOString()
      };
      return (
        <>
          <Component {...withPropName} />
          <div>
            style={{
              position: "absolute",
              left: mouse.x,
              top: mouse.y,
              width: "25px",
              height: "25px",
              backgroundColor: "red"
            }}
          >
            cat
          </div>
        </>
      );
    }
  };
}

The above solution is moot point now, use React hooks instead.

Monday, August 17, 2020

Center

.container {
    min-height: 100vh; 
    
    display: flex;
    justify-content: center;
    align-items: center;
}
Details: scotch.io: Centering things with CSS Flexbox

Sunday, August 16, 2020

Create React App with TypeScript and PnP (no npx)

#!/bin/zsh

if [ $# -eq 0 ] ; then
	echo "Pass the name of project"
	exit 1
fi

yarn set version berry

NAME="$1"

yarn dlx create-react-app $NAME --template typescript 

cd $NAME
yarn dlx @yarnpkg/pnpify --sdk vscode

TO_DECLARE="declare module '@testing-library/react';"
printf $TO_DECLARE >> src/react-app-env.d.ts

code .
The above is same as https://www.anicehumble.com/2020/08/create-react-app-with-typescript-and-pnp.html 

The previous one does not create hidden directory(.yarn) and file (.yarnrc.yml) on the parent directory of the project, while the script above do.

The advantage of the script above is almost everything works out of the box, but you just have to tolerate the creation of .yarn directory and .yarnrc.yml file on the directory where you run the create-react-app

Looks like it is safe to run "yarn set version berry" once on the home directory if you don't have any project that is dependent on yarn version 1. Setting yarn to berry on home folder would make yarn use the version 2 globally. With that said, the "yarn set version berry" above can be removed from the script.

If you set the yarn to version 2 globally and you need to go back to version 1, just delete the .yarn directory and .yarnrc file, yarn will run as version 1 again.

Saturday, August 15, 2020

Create React App with TypeScript and PnP

#!/bin/zsh

if [ $# -eq 0 ] ; then
	echo "Pass the name of project"
	exit 1
fi

NAME="$1"

npx create-react-app $NAME --template typescript
cd $NAME

yarn set version berry

yarn remove typescript
yarn add -D typescript
yarn dlx @yarnpkg/pnpify --sdk vscode

TO_DECLARE="declare module '@testing-library/react';"
printf $TO_DECLARE >> src/react-app-env.d.ts

TO_IGNORE="
.yarn/*
!.yarn/releases
!.yarn/plugins
!.yarn/sdks
!.yarn/versions
.pnp.*
"
printf $TO_IGNORE >> .gitignore

code .
https://reactjs.org/docs/create-a-new-react-app.html
https://next.yarnpkg.com/getting-started/install#updating-to-the-latest-versions
https://stackoverflow.com/questions/54954337/is-it-possible-to-use-yarn-pnp-with-typescript-vscode
https://create-react-app.dev/docs/adding-typescript/
https://yarnpkg.com/advanced/qa#which-files-should-be-gitignored


Another way: https://www.anicehumble.com/2020/08/create-react-app-with-typescript-and-pnp-no-npx.html

npm is installing...

Create Angular with authentication project on macOS

#!/bin/zsh

if [ $# -eq 0 ] ; then
	echo "Pass the name of project"
	exit 1
fi

NAME="$1"

mkdir $NAME
cd $NAME
dotnet new sln --name $NAME
dotnet new angular -o $NAME -au Individual
dotnet sln $NAME.sln add $NAME/$NAME.csproj
open $NAME.sln

Thursday, August 6, 2020

Basic drag and drop (no back-end)

let dropArea;

document.addEventListener('DOMContentLoaded', () => {
    dropArea = document.getElementById('drop-area');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => dropArea.addEventListener(eventName, preventDefaults, false));
    ['dragenter', 'dragover'].forEach(eventName => dropArea.addEventListener(eventName, highlight, false));
    ['dragleave', 'drop'].forEach(eventName => dropArea.addEventListener(eventName, unhighlight, false));

    dropArea.addEventListener('drop', handleDrop, false);
}, false);





function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}



function highlight(e) {
    dropArea.classList.add('highlight');
}

function unhighlight(e) {
    dropArea.classList.remove('highlight')
}


function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;

    handleFiles(files);
}


function handleFiles(files) {
    // console.log(files);
    // alert(Array.isArray(files)); // false
    // alert(Array.isArray(Object.values(files))); // true
    // alert(Array.isArray([...files])); // true

    // this won't work:
    //      files.forEach(uploadFile);

    [...files].forEach(uploadFile);
}

function uploadFile(file) {
    alert('uploading ' + file.name);
}
<head>


    <script src='index.js'></script>

    <style>
        html {
            box-sizing: border-box;
        }

        *,
        *:before,
        *:after {
            box-sizing: inherit;
        }

        * {
            margin: 0;
            padding: 0;
        }

        #drop-area {
            border: 2px dashed #ccc;
            border-radius: 20px;
            width: 480px;
            font-family: sans-serif;
            margin: 100px auto;
            padding: 20px;
        }

        #drop-area.highlight {
            border-color: purple;
        }

        p {
            margin-top: 0;
        }

        .my-form {
            margin-bottom: 10px; 
        }

        #gallery {
            margin-top: 10px;
        }

        #gallery img {
            width: 150px;
            margin-bottom: 10px;
            margin-right: 10px;
            vertical-align: middle;
        }

        .button {
            display: inline-block;
            padding: 10px;
            background: #ccc;
            cursor: pointer;
            border-radius: 5px;
            border: 1px solid #ccc;
        }

        #fileElem {
            display: none;
        }
    </style>

</head>

<body>

    <div id="drop-area">
        <div id="my-form">
            <p>Upload multiple files with the file dialog or by dragging and dropping images onto the dashed region</p>
            <input type="file" id="fileElem" multiple="multiple" accept="image/*" onchange="handleFiles(this.files)">
            <label for="fileElem" class="button">Select some files</label>
        </div>
    </div>


</body>

Wednesday, August 5, 2020

FileList.forEach

We can't use forEach on FileList data structure. FileList is an object, not an array. To convert it to array, we have to use Object.values, or use spread operator:
function handleFiles(files) {
    console.log(files);
    alert(Array.isArray(files)); // false
    alert(Array.isArray(Object.values(files))); // true
    alert(Array.isArray([...files])); // true

    // this won't work:
    //      files.forEach(uploadFile);

    [...files].forEach(uploadFile);
}

function uploadFile(file) {
    alert('uploading ' + file.name);
}