Author Archives: purpleblob

console.log and React Native

The easiest way to view console.log messages is using Chrome.

Select CTRL+M within your Android emulator then select Debug JS Remotely. This will start a Chrome browser window and connect it to a debugger session.

As usual within Chrome, type CTRL+SHIFT+I to view the dev tools and ensure the Console is displayed, now you should see console.log messages in the Chrome console tab.

warn and error

Alternative to using console.log, we can use console.warn and console.error which will display yellow and red pop-ups within the emulator, which Debugging-React Native states are disabled within production builds.

Standalone dev-tools

Interestingly the standalone dev tools seem not to display console.log messages. I think I read something on the chat on the React GitHub issues which suggests console logging is not part of React devtools but supplied by Chrome. However, standalone React devtools offers more debugging tools – such as viewing props/state etc.

To try out the standalone dev tools, run the following

npm install -g react-devtools

Now run

react-devtools

React Native “Hello World”

This posts assumes you’ve installed the Android studio. I won’t go through the steps for installing as, to be honest, I’ve had an installation too long to recall any steps.

Getting started

To begin with we need to use npm or yarn to add the react native scaffolding application.

yarn add global create-react-native-app

Assuming everything’s installed we can now run

yarn create-react-native-app helloworld

Replace helloworld with your application name.

You’ll then be prompted for the template to use, managed workflow, blank, blank (TypeScript), tabs or bare workflow, minimal or minimal (TypeScript).

Let’s choose minimal (TypeScript).

Next you’ll enter the name and displayName or your application, finally you’ll be prompted to install dependencies, select Yes.

From our application folder we can run

yarn android
yarn ios

In this case I’m working on Android, so before we go any further you need to run up one of the installed Android emulators before running the next step.

Now run

yarn start

which will run react-native start followed by

yarn android

in another terminal run. This will run react-native run-android.

If all goes well then the emulator should display some text (depending on the template you used).

Using the emulator

In emulator type r r in quick succession in the emulator to reload your application. Or you can enable automatic/hot loading by pressing CTRL+M in the emulator and selecting Enable Live Reload.

Problems

Whilst setting up Android studio on Linux or Windows you need to make sure ANDROID_HOME, ANDROID_PLATFORM_TOOLS and ANDROID_SDK_ROOT environment variables are set up. For example on Windows these are

  • ANDROID_HOME – C:\Users\<Username>\AppData\Local\Android\Sdk
  • ANDROID_SDK_ROOT – C:\Users\<Username>\AppData\Local\Android\Sdk
  • ANDROID_PLATFORM_TOOLS – C:\Users\<Username>\AppData\Local\Android\Sdk\platform-tools

Hello World

At this point, hopefully we’ve got everything running so let’s open App.tsx and replace

<Text>Open up App.tsx to start working on your app!</Text>

with

<Text>Hello World</Text>

Double clicking r in the emulator will reload the application displaying Hello World. So we’re on our way to the first React Native application.

Renaming a git branch

Occasionally you need to rename a branch you’re working on in git. The following shows how to rename the branch and push commits (assuming the branch had already been pushed) to a remote location

Note: if the branch has not been pushed to a remote location you only need to use the first two commands

  • git checkout <old_branch_name>
  • git branch -m <new_branch_name>
  • git push origin –delete <old_branch_name>
  • git push origin -u <new_branch_name>

Storybook and state (also uses @sambego/storybook-state)

There’s several ways to setup your components for testing within Storybook to allow us to change our component’s properties – using Knobs or creating wrapper components to encompass state changes through to hooking up to a redux store.

Let’s look at an example of wrapping our component within a story.

So I have an AppBar within a selection component. I want to see the story maintain the state changes when the user changes the selection. Now, no actual state is stored within the component itself as it’s passed up the component hierarchy to a parent component and/or redux store. This means, without setting up a parent component or redux store the selection changes but the actual value on the component remains the same.

One way to achieve this is to create a wrapper parent component, i.e. a minimal wrapper component around our component under test, for example

class WrapperComponent extends React.Component<any, any> {
  constructor(props) {
    super(props);

    this.state = { ...props }
  }

  render() {
    const props = { 
      ...this.props,
      onSelectionChanged: (selected, _) => this.setState({selected: selected}),
      selected: this.state.selected
    }

    return <ComponentUnderTest {...props} />
  }
}

So as you can see, the ComponentUnderTest is wrapped in a WrapperComponent and hooked up to props along with state changes, now we simply have the story return the WrapperComponent, i.e.

const props = {
  selected: 'None'
}

return <WrapperComponent {...props}/>

Easy enough and could be rewritten to make it more generic, but there’s an alternative and that’s to use something like @sambego/storybook-state

yarn add -D @sambego/storybook-state

In which case we can write our story like this instead

import { Store, State } from "@sambego/storybook-state";

const storeState = new Store({
  selectedPublicQuery: "None"
});

storiesOf("ComponentUnderTest", module)
  .add("default", () => {
    return (
      <State store={storeState}>
        {state => 
          <ComponentUnderTest selected={state.selected} 
              onSelectionChanged={(selected, _) => storeState.set({selected: selected})}/>
          }
        </State>
      );
  });

Storing extra data within your HTML elements using data-* attributes

I came across a simple problem, I have an array of objects in React with a name (something to display to the user) and an expression tree (which makes up a query associated with the name).

What I wanted to do is that when a name is selected in a material-ui Select component, that it then passes the name and the expression data to a handler.

Ofcourse there are several ways to achieve this but this is a really simply solution. We create an array of MenuItem‘s for the Select and we store the expression tree along with the MenuItem

If you take a look at Using data attributes you’ll see that HTML5 has a way of adding attributes to an element using the data-* syntax.

The name of the attribute to be added simply starts with data-, for example data-expression and now when the Select onChange event is handled, we can get at, not only the value selected but also the data attribute value.

Here’s an example of us setting up a MenuItem

return [{name: "None", expression: undefined}]
  .concat(publicQueries).map(e => {
    return <MenuItem key={e.name} 
      value={e.name} 
      data-expression={e.expression}>{e.name}</MenuItem>
});

Notice that we simply declare the data-expression and assign some data to it. Nothing special here.

Now within the onChange handler of the Select component we might have a handler like this

handleOnChange(e: any, child?: any) {
   const selecteNamed = e.target.value;
   const selectedExpression = child.props['data-expression'];
   // do something useful with these
}

Debugging redux

Whilst developing our UI and using redux to store our model things can get complicated when trying to understand what’s going on – did the reducer get called, what’s the state of the data in redux etc.

I’m using storybook primarily for my own testing, whilst the information below is not specific to storybook, it is a useful way to keep this stuff out of the production code.

First we need to add Chrome (or Firefox) extensions/add-ons to enable us to use the redux viewer (see https://github.com/zalmoxisus/redux-devtools-extension). When installed a Redux option should appear in the Chrome (or Firefox) debug tools and selecting it will display the redux extension which give us a way to see each dispatch message, the changes in the redux store and dig into what’s currently stored in redux.

Let’s start tings off by installing the following

yarn add redux-devtools-extension -D

Now we need to plug the dev tools into the redux store, so I’m creating a store in my story and the code looks something like this (where myReducer is obviously the reducer I’m using, initialState is obviously the state I wish to prime the redux store with, i.e. my test data). In the example below I’m using the middleware, the redux-promise-middleware this is all passed into the composeDevTools which is basically the link to the previously installed Chrome (or Firefox) dev tools.

import { composeWithDevTools } from 'redux-devtools-extension';

const store = createStore(myReducer, initialState, 
  composeWithDevTools(applyMiddleware(promiseMiddleware)));

That’s all there is to it, now run your code up, display the dev tools in Chrome (or Firefox) and select the Redux option then interact with your UI to see redux dispatched message etc.

Promises within your Redux code

You’ve created your Redux reducer code and you want to get data from a remote location using fetch or axios etc. or for that matter any functionality that runs asynchronously and returns a Promise.

Let’s look at an example of some code contrived code which hopefully makes things a little clearer

export const queryDataSource = (query: string) => {
  return {
    type: ActionType.Query,
    payload: new Promise<any>((resolve, reject) => {
      // simulate a async query
      setTimeout(() => {
        resolve();
      }, 3000);
    });
  };
}

In this example code, I wanted to make it really obvious what was going on under the hood, hence we return a Promise as the payload and the promise could encapsulate a server call, but in this case we”ll simulate this with a simple timeout.

We’d now normally handle this in a switch statement like this

  switch(action.type) {
    case ActionType.Query:
      return {
        ...state,
        data: action.payload
      };

However this isn’t what we really want to happen as the payload is a Promise. What we want is to handle the change in Promise state in an asynchronous way.

Most likely we’ll want a flag in our redux data which is bound to a property that alerts the user when an asynchronous operation starts (i.e. shows a progress indicator), then alerts the user to the operation completing and also displays errors in the operation fails and ofcourse stores the results of the operation into the redux store.

This is all fairly simple to do in code using a Promise and with redux-promise-middleware it’s equally simple to do with redux. This middleware converts the Promise into three separate events which can be handled within the redux switch function.

To add redux-promise-middleware, we do the following

  • Run yarn add redux-promise-middleware
  • Next we need to add the promise middle ware to our store creation, for example using applyMiddleware(promiseMiddleware) such as the example below
    import promiseMiddleware from 'redux-promise-middleware';
    
    const store = applyMiddleware(promiseMiddleware)(createStore)(
      combineReducers({
        queryReducer,
        connectionReducer
      })
    );
    

The promise middleware will now change the name of our actions, for example assuming ActionType.Query (in the code earlier) is the string “QUERY” then the promise middleware suffixes this string with _PENDING (when the promise is first returned), _FULFILLED (when the promise successfully completes) and _REJECTED (when the promise fails, i.e. an error).

So it’s easy to write the following to use in the redux switch

const PENDING = actionType => `${actionType}_PENDING`;
const FULFILLED = actionType => `${actionType}_FULFILLED`;
const REJECTED = actionType => `${actionType}_REJECTED`;

Now our switch case statements might look like this

case PENDING(ActionType.Query):
   return {
      ...state,
      queryError: undefined,
      runningQuery: true
   };
case FULFILLED(ActionType.Query):
   return {
      ...state,
      queryResult: action.payload,
      runningQuery: false
   };  
case REJECTED(ActionType.Query):
   return {
      ...state,
      queryError: action.payload,
      runningQuery: false
   };  

In the above the PENDING action type will occur first, so we’ll ensure any error is cleared and set a property which we bind a progress indicator in the UI. If the promise fails, REJECTED is called and we could assign some error data to our store for displaying to the user, obviously FULFILLED is called when a successful completion occurs.

Updating React Component state from props

There comes a time when the state we’re storing within our React Component needs to be updated, for example I have a ToggleButtonGroup which stores the state for the currently pressed/selected child item (i.e. you press a button in the group and the other’s deselect etc. basically a radio button).

When the component is created we might set our state from the properties like this

constructor(props) {
   super(props);

   this.state = { selected: this.props.selected }    
}

but the constructor is not called again, so what if our container component needs to change the state in our ToggleButtonGroup, so that when the properties are updated so that the ToggleButtonGroup reflects the property changes in the state.

Note: without some code in place to handle prop to state synchronisation will likely have state out of sync with expected values/behaviour.

We can use the componentDidUpdate function like this to update our state

componentDidUpdate(prevProps) {
   if(this.props.selected != prevProps.selected) {
      this.setState({selected: this.props.selected});
   }  
}

This occurs after the properties have been updated. See componentDidUpdate for more information.

You should have the guard to only change the state if the property actually changed.

componentDidUpdate is not called

The likely reason that the componentDidUpdate function is not called is if shouldComponentUpdate returns false.

getDerivedStateFromProps

An alternative to componentDidUpdate is to write a static function named getDerivedStateFromProps into your components/class. This is invoked before the render function for both initial and subsequent updates. I’ve not used this so best to read more at getDerivedStateFromProps.

Deprecated method

This method has been deprecated, but in case you come across it, we can use the component lifecycle function componentWillReceiveProps to achieve the same synchronisation of props to state. For example

componentWillReceiveProps(newProps) {
   if(newProps.selected != this.props.selected) {
      this.setState({selected: newProps.selected});
   }
}

PropTypes

PropTypes are used in React components to specify type information etc. If (as I am) you’re using TypeScript then for the most part such type extra information is not really required as we get a similar functionality via TypeScript interfaces. However, you’ll see these used a lot in JSX files where. not only can you define the expected types, but also the expected values.

To install

yarn add prop-types

PropTypes are only available in development mode which makes sense for the most part, so you would still need runtime checking on values supplied by the end user or the likes.

The usual way to write our propTypes in a JSX file is like this

import React from 'react';
import PropTypes from 'prop-types';

class Company extends React.Component {
    render() {
        return <div> 
        <h1>{this.props.name}</h1>
        {this.props.country ? <p>Country: {this.props.country}</p> : null}
        {this.props.size ? <p>Size: {this.props.size}</p> : null}
        </div>;   
    }
}

Company.propTypes = {
  name: PropTypes.string,
  country: PropTypes.string,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
};

export default Company;

If we now change App.tsx to just have this

const App: React.FC = () => {
  return (
    <Company name="My Company" size="mega" />
  );
}

You’ll find this runs but an error log in your preferred browser debug tools will show that “maga” is not a valid option, because obviously it wasn’t oneOf the supplied options.

Let’s now change the Company.jsx file to a .tsx extension.

This will fail to transpile with an error such as “Type ‘{ name: string; size: string; }’ is not assignable to type ‘IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>‘.”

Instead, we can use interfaces within TypeScript to handle the type checking at transpile time, hence this code gives us a similar set of function to the JSX version

type Size = 'small' | 'medium' | 'large';

interface CompanyProps {
  name?: string,
  country?: string,
  size?: Size
}

class Company extends React.Component<CompanyProps> {

    render() {
        return <div> 
        <h1>{this.props.name}</h1>
        {this.props.country ? <p>Country: {this.props.country}</p> : null}
        {this.props.size ? <p>Size: {this.props.size}</p> : null}
        </div>;   
    }
}

References

prop-types
ts-proptypes-transformer

Code editor for React

This is a quick post to say, if you’re looking for a JavaScript code editor UI for your application, the react-ace editor has so far proven itself very useful.

Install via yarn add react-ace and you’ll also want yarn add brace for themes, syntax colour.

Now import the dependencies like this

import AceEditor from "react-ace";
import "brace/mode/javascript";
import "brace/mode/python";
import "brace/theme/monokai";
import "brace/theme/github";

This includes two themes, monokai and GitHub for you to try along with two language colourings, in the form of javascript and python.

Now to use the editor, just drop the following code into your application

<AceEditor mode="python" //javascript
  theme="github" //monokai
  width="100%"
  onChange={this.handleOnChange}
  name="AceEditor"
  editorProps={{$blockScrolling: true}}
  value={code}
  fontSize={16}
/>          

In this example we’d have an onChange handler to store the changed text in from the editor, the value={code} is the source code that is initially displayed.