Enzyme

Enzyme is a Javascript testing utility for React. In the below tutorial I will show you how to get it working with your react classes.

Below you begin be sure to following the tutorial on Flask: React Website.

*** If you don’t have a .babelrc file setup and configured then it won’t work. This is required.

Folder Structure:
  • Inside testApp create the following:
    • folder: tests
      • folder: home
        • file: home.js
      • file: dom.js
      • file: helpers.js
Install NPM Modules:
npm install enzyme --save-dev
npm install enzyme-adapter-react-16 --save-dev
npm install ignore-styles --save-dev
npm install chai --save-dev
npm install jsdom --save-dev
npm install mocha --save-dev
npm install sinon --save-dev
Package.json:

Under “scripts” add the “test” run command.

"test": "mocha --require babel-core/register --require ignore-styles --require ./tests/helpers.js --require ./tests/dom.js --recursive \"./tests/**/*.js*\""
dom.js:

This will setup all the dom for enzyme.

var jsdom = require("jsdom");
const { JSDOM } = jsdom;
var exposedProperties = ["window", "navigator", "document"];
const { document } = (new JSDOM("<html><head></head><body><div class='container-body' id='app'></div></body></html>")).window;
global.document = document;
global.window = document.defaultView;

Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === "undefined") {
    exposedProperties.push(property);
    global[property] = document.defaultView[property];
  }
});

Object.keys(window).forEach((key) => {
    if (!(key in global)) {
        global[key] = window[key];
    }
});

//This is so jquery is available if using $
global.$ = require("jquery");
//This is so jquery is available if using jQuery
global.jQuery = require("jquery");
//This is so L is available if using leaflet otherwise don't include
global.L = require("leaflet");
global.navigator = global.window.navigator;
helpers.js:

This just set’s up enzyme configuration and allows sinon, etc through to each javascript test file.

import { expect } from "chai";
import { sinon, spy } from "sinon";

var enzyme = require("enzyme");
var Adapter = require("enzyme-adapter-react-16");

enzyme.configure({ adapter: new Adapter() });

global.expect = expect;
global.sinon = sinon;
global.spy = spy;
global.mount = enzyme.mount;
global.render = enzyme.render;
global.shallow = enzyme.shallow;
home.js:

*** it should be mentioned that the component must be exported. If your file has ReactDOM.render in it then nothing will work correctly. Must be an exported component. So if you followed the tutorial mentioned above then you will need to adjust home.jsx file to mimic this.

import React from "react";
import {Home} from "../../app/home/js/homeComponent.jsx";

describe('HomeComponent', () => {
	it('Tests that componentdidmount got called', () => {
		global.spy(Home.prototype, 'componentDidMount');
		const wrapper = mount(<Home />);
		expect(Home.prototype.componentDidMount.calledOnce).to.equal(true);
	});
});

React, Babel + Eslint Configuration

If you want to configure your npm package to have JavaScript static code analysis then you will need to configure some form of js linter. For the purposes of this demo I will use eslint.

Before We Begin:

Packages:

Package Installations:

npm install --save-dev babel
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-es2015
npm install --save-dev babel-eslint //OPTIONAL
npm install --save-dev eslint
npm install --save-dev eslint-loader
npm install --save-dev eslint-plugin-react
npm install --save-dev uglifyjs-webpack-plugin

Webpack.config.js:

Webpack 3 Plugins

Add “NoEmitOnErrorsPlugin” to ensure that emitting doesn’t occur if errors are encountered.

Add “UglifyJsPlugin” to minimize your js

Add “AggressiveMergingPlugin” to get more aggressive chunk merging.

Don’t forget the loaders for babel and eslint.

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

#Under module.exports add
plugins: [
    	new webpack.NoEmitOnErrorsPlugin(),
    	new UglifyJsPlugin(),
    	new webpack.optimize.AggressiveMergingPlugin()
],
module: {
    	loaders: [
			{
				enforce: "pre",
				test: /\.jsx?$/,
				exclude: /(node_modules|thirdparty)/,
				loader: "eslint-loader",
			},
			{
				test: /\.jsx?$/,
				exclude: /(node_modules)/,
				loader: "babel-loader",
				query: {
					presets: ["es2015","react"],
				}
			},
    	]
}


.eslintrc

You can set anything in your .eslintrc file. Here are just some that I use. All the rules starting with “react” are from “eslint-plugin-react” package.

{
    "parser": "babel-eslint",
    "env": {
        "browser": true,
        "mocha": true,
        "es6": true
    },
    "globals": {
        "require": true
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "new-cap": 0, //disabled 
        "strict": 0, //disabled 
        "semi": [2, "always"], //semi-colon required
        "no-underscore-dangle": 0, //no underscores before and after off
        "no-use-before-define": 1, //Make sure you define then use
        "eol-last": 0, //File doesn't need a newline at end
	"no-trailing-spaces": [2, { skipBlankLines: true }],
        "no-unused-vars": [1, {"vars": "all", "args": "none"}],
        "quotes": [
            2,
            "double"
        ],
        "jsx-quotes": [2, "prefer-double"], //Must use double quotes
        "react/jsx-boolean-value": 1, //warning when no value is set for boolean
        "react/jsx-no-undef": 2, //error: undeclared variables
        "react/jsx-uses-react": 1, //Warn: Prevent incorrectly unused
        "react/jsx-uses-vars": 1, //Warn: Prevent unused variables
        "react/no-did-mount-set-state": 0, //Off: Prevent setState in componentDidMount
        "react/no-did-update-set-state": 0, //Off: Prevent setState in componentDidUpdate
        "react/no-multi-comp": 1, //Warn: Prevent only one component per file
        "react/no-unknown-property": 1, //Warn: Prevent unknown DOM
        "react/react-in-jsx-scope": 1, //Warn: Prevent missing React
        "react/self-closing-comp": 1 //Warn: Prevent extra closing tags
    }
}

.eslintignore

Use this file to ignore any files or folders.

app/folder/**

.babelrc

This is the config file for babel.

{
 "presets": [ "es2015" ]
}

Package.json

If you want to run eslint from npm then you have to modify your package.json with the following line. –ext is what extension you want to test against.

If you want a third party to run reports on your eslint then add to the end “-f checkstyle > eslint.xml

"scripts": {
    "eslint": "eslint app --ext .jsx --ext .js"
}

Django: React Website

In this tutorial I will demonstrate how to create a Django + React website using Django 2.0. You must have Eclipse installed before you continue. If you have it already installed and configured you can continue on. We will require Postgres 9.4, nodejs before you continue. You can get Nodejs from here. You can get Postgres 9.4 from here.

Pip Django Install:
pip install django
pip install django-webpack-loader
Django Version:

If you are not sure what version you are running do the following

python -c "import django; print(django.get_version())"
Eclipse Create Project:

 

 

 

 

 

 

Eclipse Setup Project:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Eclipse Django DB Settings:

 

 

 

 

 

 

 

 

 

 

 

 

 

Eclipse Django Setup Successful:

Once you click “Finish” your project will look like the following.

 

 

 

Folder Structure:
  • Under djangoApp project.
  • folder: static
  • folder: djangoApp
    • folder: templates
      • file: index.html
      • folder: base
        • file: base.html
  • folder: assets
    • folder: bundles
    • folder: js
      • file: index.jsx
Node:

Inside the djangoApp application do the following

npm init
npm install --save-dev jquery react react-dom webpack webpack-bundle-tracker babel-loader babel-core babel-preset-es2015 babel-preset-react
npm install create-react-class --save
webpack.config.js:
var path = require('path')
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')

module.exports = {
    //the base directory (absolute path) for resolving the entry option
    context: __dirname,
    //the entry point we created earlier. Note that './' means 
    //your current directory.
    entry: {
		"index": [path.resolve(__dirname, "./assets/js/index.jsx")],
	},
	output: {
		path: path.resolve('./assets/bundles/'),
		filename: "[name]-[hash].js",
	},
    plugins: [
        //tells webpack where to store data about your bundles.
        new BundleTracker({filename: './webpack-stats.json'}), 
        //makes jQuery available in every module
        new webpack.ProvidePlugin({ 
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery' 
        })
    ],
    module: {
        loaders: [
		{
			test: /\.jsx?$/,
			exclude: /(node_modules)/,
			loader: 'babel-loader',
			query: {
				presets: ['react','es2015']
			}
		}
        ]
    }
}
djangoApp\Settings.py:

Installed Apps

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'webpack_loader',
]

Add/Edit the following template directive

TEMPLATES = [
 {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'djangoApp', 'templates'),],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},]

Add the following static directive

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'assets'),
]

Modify DATABASES

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'YOUR_DB_NAME',
        'USER': 'YOUR_USER',
        'PASSWORD': 'YOUR_PASSWORD',
        'HOST': 'localhost',
        'PORT': 5432
    }
}

Webpack Loader

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
    }
}
djangoApp\views.py:

We will create our index page view. Notice the third dict. Those are variables passed to the template to make our site dynamic

from django.shortcuts import render

def index(request):
    return render(request, 'index.html', {'title': 'Index Page', 'script_name': 'index'})
djangoApp\urls.py:

Add the following imports

from django.conf.urls import url
#This is the index view we created above
from djangoApp.views import index

urlpatterns = [
    url(r'^$', index, name='index'),
    path('admin/', admin.site.urls),
]
djangoApp\templates\base\base.html:

Let’s setup our base template and setup our blocks that the other templates will inherit from.

<html>
	<head>
		<title>{% block title %}{% endblock %}</title>
	</head>
	<body>
		{% block content %}
		{% endblock %}
	</body>
</html>
djangoApp\templates\index.html:

The important parts here are the extends otherwise your base.html template won’t be inherited. As well the {% with %} and title variable makes our template dynamic and allows us to incorporate react in our site.

{% extends "base/base.html"  %}
{% load render_bundle from webpack_loader %}
{% load staticfiles %}
{% block title %}
	{{title}}
{% endblock %}
{% block content %}
	<div id="container"></div>
	{% with script=script_name %}
		{% render_bundle script 'js' %}
	{% endwith %} 
{% endblock %}
assets\js\index.jsx:

This is our react class.

var React = require('react');
var ReactDOM = require('react-dom');
var createReactClass = require('create-react-class');

var App = createReactClass({
    render: function() {
        return (
            <h1>
            React App Page
            </h1>
        )
    }
});

ReactDOM.render(<App />, document.getElementById('container'));
Database Setup/Migration:

For this tutorial we used postgres. At this time please make sure you create your djangoApp db and user you specified in the settings.py file. Then run the following commands in order.

#Migrates the auth
python manage.py migrate auth
#migrates the rest
python manage.py migrate
#Create the user for accessing the django admin ui
#This will ask you for user names and passwords. Don't make it the same as in your settings.py file.
python manage.py createsuperuser
Start Server:
webpack -p
python manage.py runserver

Your site is now running at http://localhost:8000.

Your admin site is now running at http://localhost:8000/admin/.

 

References:

I used this video as a guideline to get the project started. However some didn’t work right and needed to adjust and made adjustments to require just one template, etc.

React: Leaflet Markers

This entry is part 9 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add a marker to the map. Refer to the documentation for more information.

Before We Begin:

Text:

LayerGroup onAdd Method

//Define the marker. Since this is text based their is no icon but instead a divIcon
this.textMarker = L.marker([20.5, -0.09],{
	icon: L.divIcon({
		iconSize: [100,16],
		iconAnchor: [22, 30],
		className: "",
	}), 
	zIndexOffset: 75,
});

//Sets the text
this.textMarker.options.icon.options.html = "This is my text";

//Adds the text marker to the layer
this.addLayer(this.textMarker);

LayerGroup onRemove Method

//Remove the text marker you just added
this.removeLayer(this.textMarker);

Results: Now you will see as you turn the layer on and off from the context menu the text will show or hide.

Icon:

Import Image:

import myImagefrom "../images/myImage.png";

Create Icon/Marker onAdd Method

//Define the icon you will be using
var myIcon = L.icon({
	iconUrl: myImage,
	iconSize:     [75, 75], // size of the icon
	iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
});

//Define the icon based marker
this.marker = L.marker([20.5, -40.09],{
	icon: myIcon,
	opacity: 0.7,
	zIndexOffset: 30
 });

//Adds the icon marker to the layer
this.addLayer(this.marker);

onRemove Method

//Remove the marker you just added
this.removeLayer(this.marker);

Results: Now you will see as you turn the layer on and off from the context menu the icon will show or hide.

Set Latitude/Longitude:

You can set the latitude and longitude in one of two ways.

//Set the latitude and longitude

//Method 1:
L.marker([20.5, -0.09])

//Method 2:
this.textMarker.setLatLng([20.5, -0.09]);

Event(s):

onClick

marker.on("click", function(e) {
	var marker = e.target;
	//Do my work here
}.bind(this));

MouseOver

marker.on("mouseover", function(e) {
	var marker = e.target;
	//Do my work here
}.bind(this));

MouseOut

marker.on("mouseout", function(e) {
	var marker = e.target;
	//Do my work here
}.bind(this));

Popup:

BindPopup

marker.bindPopup(L.popup(),{
	offset: L.point(0,-10) //You can add an offset if you want to
});

OpenPopup

Let’s say you want to open the popup during a mouseover event.

marker.on("mouseover", function(e) {
	var marker = e.target;

	//Set the content to display in the popup
	marker.setPopupContent("My Text");
	//Now open the popup
	marker.openPopup();
}.bind(this));

ClosePopup

Let’s say you want to open the popup during a mouseout event.

marker.on("mouseout", function(e) {
	var marker = e.target;
	//Close the popup now
	marker.closePopup();
}.bind(this));

React: Leaflet Icon

This entry is part 8 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add an icon to the map. Refer to the documentation for more information.

Before We Begin:

Create Folders/Files:

  • app
    • folder: leaflet
      • folder: images
        • file: yourimage.png

Import Image(s):

import yourimage from "../images/yourimage.png";

Create Icon:

var myIcon = L.icon({
     iconUrl: plusimg,
     iconSize:     [75, 75], // size of the icon
     iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
});

Add to Map:

[51.5, -0.09] refers to the position on the map you want to add it to. Refer to the marker tutorial for further information on markers.

L.marker([51.5, -0.09], {icon: myIcon}).addTo(this.map);

React: Leaflet Control

This entry is part 7 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add a control to the map. Refer to the documentation for more information.

Before We Begin:

LayerControl

You can now do anything you want to do here.

var MyControl = L.Control.extend({
    onAdd: function (map){
        //Reference to the map
        this._map = map;

        //This is the container to return so it is available on the map
        var container = L.DomUtil.create("div");
        return container;
    },
    onRemove: function(){
        //Removes the control
        L.Control.prototype.onRemove.call(this);
        this._map = null;
    }
});

Add Control to Map

The options you add in the class definition are the options that the control gets.

var myControl = new MyControl({ position: "bottomright"});
myControl.addTo(this.map);

React: Leaflet LayerGroup

This entry is part 6 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add a layer group control. Refer to the documentation for more information.

Before We Begin:

LayerGroup

You can now do anything you want to do here.

var MyLayerGroup = L.LayerGroup.extend({
    onAdd: function(map) {
        //Reference to the map
        this._map = map;
    },
    onRemove: function(){
        //Removes the layer
        L.LayerGroup.prototype.onRemove.call(this, map);
    },
    initialize: function (options) {
        L.LayerGroup.prototype.initialize.call(this);
        //The options sent in from initialisation
        L.Util.setOptions(this, options);
    }
});

Add LayerGroup to Map

var myLayerGroup = new MyLayerGroup();
myLayerGroup.addTo(this.map);

Overlay

If you want to add the layergroup to overlays menu.

this.layerControl.addOverlay(myLayerGroup, "My Layer Group");

React: Leaflet DomEvent

This entry is part 5 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add events to your html control. Refer to the documentation for more information.

Before We Begin:

OnClick

L.DomEvent.on(htmlControl, "click", (e) => {
 	//Do your work here
});

 

 

 

React: Leaflet html Controls

This entry is part 4 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add html controls to your leaflet map. Refer to the documentation for more information.

Before We Begin:

Really you can create any html control just substitute div for whatever you want. Below are just some basic examples.

Div

var divContainer = L.DomUtil.create("div", "myClassName");

Image

var img = L.DomUtil.create("img", "myClassName");

Label

var label = L.DomUtil.create("label", "myClassName");

Span

var span = L.DomUtil.create("span", "myClassName");

Input

var input = L.DomUtil.create("input", "myClassName");

BR

var br = L.DomUtil.create("br", "myClassName");

You can modify the html control with additional values such as

#style
divContainer.style.display = "";

#id
divContainer.id = "myId";

#name
divContainer.name = "myId";

#img src
divContainer.src = "";

#title
divContainer.title = "";

#innerHTML
divContainer.innerHTML = "";

#type
divContainer.type= "checkbox";

#checked
divContainer.checked= false;


Parent Control

You can add the control to a parent control in the following way.

var divContainer = L.DomUtil.create("div", "myClassName");

var subContainer = L.DomUtil.create("div", "myClassName", divContainer);

React: Leaflet EasyButton

This entry is part 3 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add a easy button to your leaflet map. This will just be a basic example. For more information refer to the documentation.

Before We Begin:

Node Package Install:

npm install leaflet-easybutton --save

Edit app/home/leaflet/js/map.jsx:

//Add the leaflet easybutton package
require("leaflet-easybutton");
require("leaflet-easybutton/src/easy-button.css");

//Somehwere on your page add the following.


//Check out https://github.com/CliffCloud/Leaflet.EasyButton for more uses
L.easyButton("<div id="tag" class="glyphicon glyphicon-tag" />", function(btn, map) {
 	map.setView([42.3748204,-71.1161913],16);
}, { position: "topleft"}).addTo(this.map);

React: Leaflet Modal

This entry is part 2 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add a modal dialog to your leaflet map. Refer to the documentation for more information.

Before We Begin:

Node Package Install:

npm install leaflet-modal --save

Edit app/home/leaflet/js/map.jsx:

//Add the leaflet modal package
require("leaflet-modal");
require("leaflet-modal/dist/leaflet.modal.min.css");

//Somewhere on your page add the following. You can even put it on a onclick event or whatever

//Create a test control for your modal control.
this.modalContainer = L.DomUtil.create("div");
map.openModal({
	zIndex: 10000, 
	element: this.modalContainer, //The container to display in the modal 
	OVERLAY_CLS: "overlay", //This is a built in class which you can change if you want
	MODAL_CLS: "modal", //This is a built in class which you can change if you want
	height: 200, width: 200, 
	MODAL_CONTENT_CLS: "modal-content",  //This is a built in class which you can change if you want
	CLOSE_CLS: "modal-close-hide" //The property for close class
});

Edit app/home/leaflet/css/map.css:

.modal-close-hide {
	/*Class for hiding the modal*/
	display: none;
}

React: Basic Leaflet Map Example

This entry is part 1 of 9 in the series React: Leaflet

In this tutorial I will walk you through incorporating leaflet map in your application. This is just a basic setup walkthrough. We do not deal with overlays or extending controls.

Documentation:

Leaflet
Leaflet Providers

Before We Begin:

If you have not done so already refer to how to Build a React/Python Site to get your basic site up and running.

Node Package Installs:

npm install leaflet-providers --save
npm install leaflet --save

Create Needed Folders/Files:

  • app
    • folder: leaflet
      • folder: css
        • file: map.css
      • folder: js
        • file: map.jsx

Webpack:

Add the following loader for handling images to your webpack.config.js file.

{ test: /.*\.(gif|png|jpe?g|svg)$/i, loader: "file-loader?hash=sha512&digest=hex&name=[name].[ext]" }

Edit app/leaflet/js/map.jsx:

We are going to create the map control. Refer to comments below for explanations.

window.jQuery = window.$ = require("jquery");
//React packages
var React = require("react");
var createReactClass = require("create-react-class");

//Leaflet packages
import L from "leaflet";
import "leaflet/dist/leaflet.css";

//LeafLet providers
require("leaflet-providers");

//map css you will create
import "../css/map.css";

var LeafLetMap = createReactClass({
    getInitialState: function() {
        return {};
    },
    displayMap: function() {
        //Setup/initialize the map control
        window.map = this.map = L.map("map", {
            attributionControl: false, //http://leafletjs.com/reference-1.2.0.html#control-attribution
        }).setView([0,0], 1);
        
        //A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) 
        L.control.scale({ //http://leafletjs.com/reference-1.2.0.html#control-scale
            metric: false,
            imperial: true
        }).addTo(this.map);
        
        //You can check out all the free providers here https://github.com/leaflet-extras/leaflet-providers
        //Below are just examples
        this.layers = {
                OpenMapSurferRoads: L.tileLayer.provider('OpenMapSurfer.Roads'),
                HyddaFull: L.tileLayer.provider('Hydda.Full'),
                StamenTerrain: L.tileLayer.provider('Stamen.Terrain'),
                EsriWorldStreetMap: L.tileLayer.provider('Esri.WorldStreetMap'),
                EsriWorldTopoMap: L.tileLayer.provider('Esri.WorldTopoMap'),
                EsriWorldTerrain: L.tileLayer.provider('Esri.WorldTerrain'),
                OpenTopoMap: L.tileLayer.provider('OpenTopoMap'),
                OpenStreetMapBlackAndWhite: L.tileLayer.provider('OpenStreetMap.BlackAndWhite'),
                OpenStreetMapHOT: L.tileLayer.provider('OpenStreetMap.HOT')
            };

        //Add the default layer you want to use
        this.layers.OpenMapSurferRoads.addTo(this.map);

        //Add the layer control to the top left corner
        this.layerControl = L.control.layers(this.layers, {}, { position: "topleft" }).addTo(map);
    },
    componentDidMount: function() {
        //Done after mounting so that it sees the div you are going to map to
        this.displayMap();
    },
    render: function() {
        return (
            <div className="div-flex">
                <div id="map" key="map" className="map"></div>
            </div>
        );
    }
});

module.exports = { LeafLetMap:LeafLetMap };

Edit app/leaflet/css/map.css:

.map {
	/*Changes the width and height of the map*/
	height: 400px;
	width: 800px;
}

div.leaflet-top {
	/*OPTIONAL: This is only needed if your controls start going behind the map.*/
	z-index: 1001;
}

.leaflet-control-layers-toggle {
	/*Changes the width and height of the layer control*/
	height: 30px !important;
	width: 30px !important;
}

Edit app/home/js/home.jsx:

//Import your leaflet map control from the page you created above
import { LeafLetMap } from "../../leaflet/js/map.jsx";

//In the render function add your control
render: function() {
		return (
			<div className="div-flex">
		        	<LeafLetMap ref="map" />
			</div>
		);
	}

 

 

 

Javascript: Map

You can use the map function to return different results from an array to return a new array with new data.

For example if you want to build an array of controls you could do the following.

var newControls = myDataArray.map(function(rec, index){
    	        return <div></div>;
    	    });

 

JavaScript: Download Object Data

Sometimes you just want to send an object to be downloaded in which you don’t have any special requirements just download the data. To do so is really straight forward. Create the blob with the type then create the blobs object url.

var blob = new Blob([JSON.stringify(myDataObject)], {type: "application/force-download"});
url  = URL.createObjectURL(blob);

<a target="_blank" href={url} download="file.extension" />

Javascript: Math Functions

In this post I will show you how to perform math operations such as min, max, etc.

Min:

//Array
var maxValue = Math.min.apply(Math, myArray);

//Object Array
Math.min.apply(Math,myObjectArray.map(function(v){return v,key;}));

Max:

//Array
var maxValue = Math.max.apply(Math, myArray);

//Object Array
Math.max.apply(Math,myObjectArray.map(function(v){return v,key;}));

Sum:

var sumValue = myArray.reduce(function(a, b) { return a + b; }, 0);

Average:

var avgValue = sumValue / myArray.length;

Standard Deviation:

var stdevValue = Math.sqrt(sumValue);

Python: Flask Resource

This tutorial helps setup flask restful api’s.

Install Python Packages:

Open cmd and navigate into your testApp folder and run the following commands.

pip install flask-RESTful && pip freeze > requirements.txt
__init__.py:

On the init of your application you will need to setup flask_restful. There are config options you could set for config.py. Look into it!

from flask_restful import Api
api = Api(app)

#Add api endpoints
#Get
api.add_resource(home.views.MyResource, '/home/getMyData/')

#Post
api.add_resource(home.views.MyResource, '/home/getMyData/', methods=['POST'])
Setup home views.py:

You need to import Resource in it’s most simplistic form. However if you want to deal with request parameters add in reqparse and inputs. Inputs give you access to boolean that way a boolean can be parsed into a python boolean easily.

from flask_restful import Resource, reqparse, inputs

You can now use get, post, etc. I will give you three examples below.

Get:

class MyResource(Resource):
	def get(self):
		return {}

Get /w Parameter:

class MyResource(Resource):
	def get(self, var):
		return {}

Get /w Parameter & Request Parameter:

class MyResource(Resource):
	def get(self, var):
        	parser = reqparse.RequestParser()
        	parser.add_argument('new_request_var', type=str, default='')

        	#If you want to have a boolean request parameter do the following.
        	parser.add_argument('new_request_var_bool', type=inputs.boolean, default=False)

        	args = parser.parse_args(strict=True)
        	new_request_var = args['new_request_var']
        	new_request_var_bool = args['new_request_var_bool']

		return {}

Post:

class MyResource(Resource):
	def post(self):
		return {}

JavaScript: Node & Lodash

In this tutorial we will be giving out some quick examples of Lodash functionality. To know more go here. There are so many examples and ways of doing Lodash. Check out the documentation.

Q: What is Lodash you ask?
A: It is a toolkit of Javascript functions that provides clean, performant methods for manipulating objects and collections. It is a “fork” of the Underscore library and provides additional functionality as well as some serious performance improvements.

First thing we need to do is install it. You will need a node site already ready to go. If you don’t have one you can follow this tutorial on setting a basic one up.

npm install lodash --save

On whatever page you are working with all you need to do is add the following to where your requires are.

var _ = require('lodash');

Now we can use the functionality as we wish. I will do some basic uses below.

Array difference:

If we want to find the difference of an array to the second array. The result would be “1” because 1 is not in the second array. Notice how it does not compare the second array to the first. It’s only checking which values 2 or 1 don’t exist in the second array.

_.difference([2, 1], [2, 3])
Array uniqWith:

If you want to get the unique items in an array you could use the following. It would return “2 45 3 7 8 1” only notice that the additional 45 is not displayed. It has been removed.

_.uniqWith([2, 45, 3, 7, 8, 45, 1], __.isEqual)