Tag Archives: JavaScript

Missing .tsconfig when converting existing ReactJS project

Hi everyone,

I’ve finally decided to start learning typescript while working on a side project. The plan was to convert the existing project over using the following command:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

After restarting the web server I had expected to see a tsconfig.json file that would allow me to setup my preferred configuration. Unfortunately, mine was missing.

A bit of Googling revealed that the tsconfig file isn’t actually generated until you add a .ts or .tsx file to the project. In my case, I simply renamed an existing component and the configuration file was generated during the next startup. Note that you will also have to remove your jsconfig.json file (if you haven’t already).

Thanks to this blog for the detailed info: https://blog.bitsrc.io/why-and-how-use-typescript-in-your-react-app-60e8987be8de

String to Color – Avatar Helpers

Hi everyone,

A quick post on a helper function I came across for generating avatars. This function generates a random color for the specified string:


export const stringToColor = string => {

let hash = 0;
let i;

for (i = 0; i < string.length; i += 1) {
hash = string.charCodeAt(i) + ((hash << 5) - hash);
}

let colour = '#';

for (i = 0; i > (i * 8)) & 0xff;
colour += `00${value.toString(16)}`.substr(-2);
}

return colour;
}

Thanks to oliviertassinari: https://github.com/oliviertassinari/SplitMe/blob/c25fe62187a856386fd0c43c51859d6f973d651e/src/main/member/Avatar.js#L8-L26

Parsing Hash Args for Cognito Auth – Javascript

Hi everyone,

A quick post on a function for parsing hash args when using AWS Congito.

//jsfiddle.net/4eo7836j/embed/

Just in case the fiddle ever disappears:

const parseHashArgs = aURL => {

  aURL = aURL || window.location.href;

  var vars = {};
  var hashes = aURL.slice(aURL.indexOf('#') + 1).split('&');

  for (var i = 0; i  1) {
      vars[hash[0]] = hash[1];
    } else {
      vars[hash[0]] = null;
    }
  }

  return vars;
};

document.body.append(parseHashArgs("#id_token=testtokenval&token_type=bearer&expires_in=3600")["id_token"]);

Thanks to this link on Github: https://gist.github.com/miohtama/1570295/289d5a82e65663c9b515c88186a268c6dd1fddb7

NavLink ListItems not Applying activeClassName class when Clicked On – ReactJS React-Router MaterialUI

Hi everyone,

A bit of a hairy issue I ran into today that took a while to track down. I’m using React Router with Material UI to render a Drawer as a sidebar:

The issue was that some links were not applying the expected activeclass:


	
		
	
	<ListItemText primary={
		
			About
		
	} />

After trawling through react-router I eventually found a post on github that mentioned a similar issue: https://github.com/ReactTraining/react-router/issues/4638

The solution turned out to be wrapping all relevant components with withrouter.

Uncaught SyntaxError: Unexpected token < – ReactJS Build

Hi everyone,

A ReactJS issue I ran into after running npm run build:

Uncaught SyntaxError: Unexpected token <

This one took a while to track down but it essentially boils down to the built index.html file referencing paths relatively:

Issue: index.html was referencing
"</html".

Instead of:
"</html".

This meant that anytime a page was accessed directly it attempted to load the static files from the wrong directory. To fix it, I had to update the homepage node in package.json

Original:
...
"version": "0.1.0",
  "homepage": "./",
  "private": true,
...

Instead use:
"version": "0.1.0",
  "homepage": "/",
  "private": true,

Hopefully that’s able to help someone else out, took a while to track down!

npm ERR! missing script: flow npm ERR! A complete log of this run can be found in: – ReactJS and Flow

Hi everyone,

I ran into the following error while trying to setup flow:

npm ERR! missing script: flow
npm ERR! A complete log of this run can be found in:

To fix this, just add “flow”: “flow” as a new entry under “scripts” in your package.json file.

See the following link for more info:
https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-flow

Error Adding Card – Assembly Payments

Hi everyone,

Just working with Assembly Payments and ran into the following error while following their documentation on Capturing a Credit Card:

errors”:{“card_account”:[“Error adding card. If error persists, please contact our support team.”]

The error is pretty vague, but it does seem that the credit card info they use in the documentation has expired. I tested with another credit card and it went through:

                    promisepay.createCardAccount(token, {

                        full_name: "Bella Buyer",
                        number: "4242424242424242",
                        expiry_month: "12",
                        expiry_year: "2021",
                        cvv: "123"
                    }, success, fail)

Naming Issue
You can also hit this if you’ve only provided a first name and no last name. e.g. John instead of John Doe.

You can work around this by entering the first name twice i.e. John John. Seems a little dodgy but it is the official recommendation from Assembly payments: https://docs.assemblypayments.com/en/articles/2037287-error-error-adding-card-if-this-error-persists-please-contact-our-support-team

Official card details
I was talking to support about another issue and they mentioned the following page: https://reference.assemblypayments.com/#credit-card-data

Including an Externally Hosted Script in ReactJs

Hi everyone,

Just a quick example of how to include an externally hosted js file in a reactjs app. In index.html add your script tag as you would in a normal app:

  
    https://js.prelive.promisepay.com/PromisePay.js
  

Then in the file you plan to use the library you can add a const and reference it normally:

const promisepay = window.promisepay;

Thanks to this link for the info: https://stackoverflow.com/a/44877953/522859

Allow Number and String for PropTypes – ReactJS

Hi everyone,

A quick post on how to allow a string or number when defining PropTypes:

static propTypes = {
        numberField: PropTypes.number.isRequired,
        stringField: PropTypes.number.isRequired,
        mixedField: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired
    }

Thanks to this stackoverflow post for the info: https://stackoverflow.com/a/41808543/522859

Avoiding Wrapper Divs in ReactJs

Hi everyone,

Just a quick post on how you can avoid wrapper divs in ReactJs. It’s particularly useful when populating tables or creating parts of a larger component. Instead of the following:

return (
  
Frogs Turtles
);

You can use fragments:

import React, { Fragment } from 'react'
...
return (
  
    Frogs
    Turtles
  
);

The fragment won’t polute the dom and mean that you don’t need to add any additional styling. Check out these links for more info:
https://reactjs.org/docs/fragments.html
https://stackoverflow.com/a/49375945/522859
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html