Create a Gauge in React Native using FusionCharts
Overview
FusionCharts is a JavaScript charting library that enables you to create interactive charts, gauges, maps and dashboards in JavaScript. We have built a simple and lightweight React Native component which provides bindings for FusionCharts. The react-native-fusioncharts
component allows you to easily add rich and interactive charts to any React Native project.
In this page, we'll see how to install FusionCharts and render a gauge using the react-native-fusioncharts
component.
Installation
Install FusionCharts and the react-native-fusioncharts
component using any of the following methods:
react-native-fusioncharts
component via npm follow the steps below:react-native-fusioncharts
module
$ npm install react-native-fusioncharts --save
fusioncharts
JS files
$ npm install fusioncharts --save
react-native-fusioncharts
component for Android, follow the steps given below:- Create a folder named
assets
underandroid/app/src/main
directory if it doesn't exist. - Copy
FusionCharts
library files (node_modules/fusioncharts folder) in theassets
folder. - Create a
fusioncharts.html
file inassets
folder. Include the FusionCharts library files infusioncharts.html
file using <script> tag.
<!DOCTYPE html>
<html>
<head>
<title>FusionCharts</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body,
html {
margin: 0;
padding: 0;
overflow: hidden;
font-size: 13px;
}
#chart-container {
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
user-select: none;
-webkit-user-select: none;
overflow: hidden;
}
#loading-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
user-select: none;
-webkit-user-select: none;
}
</style>
</head>
<body>
<div id="chart-container">
<div id="loading-text">
Chart is loading...
</div>
</div>
<script type='text/javascript'>
"use strict";
(function() {
var a = Promise.resolve(),
b = {},
c = {};
(function d() {
var f = function() {
function g() {
return Math.floor(65536 * (1 + Math.random())).toString(16).substring(1)
}
return g() + g() + "-" + g() + "-" + g() + "-" + g() + "-" + g() + g() + g()
};
window.webViewBridge = {
send: function send(g, h, i, j) {
i = i || function() {}, j = j || function() {};
var k = {
targetFunc: g,
data: h || {},
msgId: f()
},
l = JSON.stringify(k);
a = a.then(function() {
return new Promise(function(m, n) {
b[k.msgId] = {
resolve: m,
reject: n
}, c[k.msgId] = {
onsuccess: i,
onerror: j
}, window.postMessage(l)
})
}).catch(function() {})
}
}, window.document.addEventListener("message", function(g) {
var h;
try {
h = JSON.parse(g.data)
} catch (i) {
return
}
b[h.msgId] && (b[h.msgId].resolve(), delete b[h.msgId]), h.args && c[h.msgId] && (h.isSuccessfull ? c[h.msgId].onsuccess.apply(null, h.args) : c[h.msgId].onerror.apply(null, h.args), delete c[h.msgId])
})
})()
})();
</script>
<!-- Include the required FusionCharts modules -->
<script type='text/javascript' src="fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="fusioncharts/fusioncharts.widgets.js"></script>
<script type='text/javascript' src="fusioncharts/themes/fusioncharts.theme.fusion.js"></script>
</body>
</html>
libraryPath
property to the FusionCharts component.
<FusionCharts
......
libraryPath={{ uri: 'file:///android_asset/fusioncharts.html' }}/>
package.json
file to bundle your assets when you want to generate a signed APK.
"scripts": {
......
"clean:build:android": "rm -rf android/app/build",
"prod:android": "npm run clean:build:android && react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res"
},
$ npm run prod:android
react-native-fusioncharts
component via npm follow the steps below:react-native-fusioncharts
module
$ npm install react-native-fusioncharts --save
fusioncharts
JS files
$ npm install fusioncharts --save
react-native-fusioncharts
component for iOS, follow the steps given below:- Create a folder named
assets
in your projectroot
if it doesn't exist. - Copy
FusionCharts
library files in theassets
folder. - Create a
fusioncharts-tpl.html
file inassets
folder. Include the FusionCharts library files infusioncharts.html
file using <script> tag.
<!DOCTYPE html>
<html>
<head>
<!-- Include the required FusionCharts modules -->
<script type='text/javascript' src="fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="fusioncharts/fusioncharts.widgets.js"></script>
<script type='text/javascript' src="fusioncharts/themes/fusioncharts.theme.fusion.js"></script>
</head>
<body></body>
</html>
build"assets
script in Application's package.json
file
"scripts": {
......
"build:assets": "fc-build-assets --fc-template ./assets/fusioncharts-tpl.html --fc-library ./assets/fusioncharts"
},
--fc-library ./assets/fusioncharts
is required when you copy FusionCharts library files in your assets
folder.Note:
fc-build-assets
is a utility binary provided by react-native-fusioncharts
to package the FusionCharts modules(.js files) referenced in template(.html file) as needed by the React Native iOS build process.
$ npm run build:assets
That completes the installation of FusionCharts and the react-native-fusioncharts
component.
Create your first gauge
Gauges are powerful tools that can showcase information using a radial or linear scale to display data.
To start with, we'll build a simple angular gauge showcasing Nordstorm's Customer Satisfaction Score as shown below.
FusionCharts Suite has 95+ chart types for you to explore. Find the complete list of chart types here.
The angular gauge is shown below:
The thresholds for the above sample have been defined using the following range:
Range | Color | Hex Code | |
---|---|---|---|
0-50 | Red | #F2726F | |
50-75 | Yellow | #FFC533 | |
75-100 | Green | #62B58F |
So, any score less than 50 is bad and is red. Any score between 50 and 75 is average and is yellow. Any score above 75 means good and are green.
Convert tabular data into JSON format
Now that you have the tabular data ready, it's time to convert it into JSON format, as FusionCharts accepts data in JSON or XML format. In this example, we will use the JSON format, as shown below:
{
// Chart Configuration
"chart": {
"caption": "Nordstorm's Customer Satisfaction Score for 2017",
"lowerLimit": "0",
"upperLimit": "100",
"showValue": "1",
"numberSuffix": "%",
"theme": "fusion",
"showToolTip": "0"
},
// Chart Data
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "50",
"code": "#F2726F"
}, {
"minValue": "50",
"maxValue": "75",
"code": "#FFC533"
}, {
"minValue": "75",
"maxValue": "100",
"code": "#62B58F"
}]
},
"dials": {
"dial": [{
"value": "81"
}]
}
}
In the above JSON:
Create the
chart
object to define the elements of the gauge.Create the
colorRange
array to set the color associated with the specific range of values.Specify
minValue
andmaxValue
within thecolor
array under thecolorRange
array.Specify the hex code of the color within the
color
array.Create the
dials
object to represent the customer satisfaction score.Create the
dial
object underdials
object to set the value of the dial in an array.
The chart object and the respective arrays contain a set of key-value pairs known as attributes
. These attributes are used to set the functional and cosmetic properties of the gauge.
Now that you have converted the tabular data to JSON format, let's learn how to render the gauge.
Render the chart
To render the chart, follow the steps below:
Include react
Include
react-native-fusioncharts
componentDefine the chart configuration in a JSON.
- Set the gauge type as
angulargauge
. Each chart type is represented with a unique chart alias. For Angular Gauge, the alias isangulargauge
. Find the complete list of gauge types with their respective alias here. - Set the width and height (in pixels).
- Set the
dataFormat
as json. - Embed the json data as the value of the
dataSource
.
- Set the gauge type as
Specify the location of
fusioncharts.html
for Android and iOS.Add
style
to the container of the chart.
The
JavaScript
code to create a chart in Android and iOS is same.
Copy the following code to app.js
file.
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import FusionCharts from 'react-native-fusioncharts';
export default class DrillDown extends Component {
constructor(props) {
super(props);
this.apiCaller = null;
this.state = {
type: 'angulargauge',
width: '450',
height: '250',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Nordstorm's Customer Satisfaction Score for 2017",
"lowerLimit": "0",
"upperLimit": "100",
"showValue": "1",
"numberSuffix": "%",
"theme": "fusion",
"showToolTip": "0"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "50",
"code": "#F2726F"
}, {
"minValue": "50",
"maxValue": "75",
"code": "#FFC533"
}, {
"minValue": "75",
"maxValue": "100",
"code": "#62B58F"
}]
},
"dials": {
"dial": [{
"value": "81"
}]
}
}
};
this.libraryPath = Platform.select({
// Specify fusioncharts.html file location
android: { uri: 'file:///android_asset/fusioncharts.html' },
ios: require('./assets/fusioncharts.html')
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.header}>A Simple Gauge</Text>
<View style={styles.chartContainer}>
<FusionCharts
type={this.state.type}
width={this.state.width}
height={this.state.height}
dataFormat={this.state.dataFormat}
dataSource={this.state.dataSource}
libraryPath={this.libraryPath}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10
},
header: {
fontWeight: 'bold',
fontSize: 20,
textAlign: 'center',
paddingBottom: 10
},
chartContainer: {
height: 400,
borderColor: '#000',
borderWidth: 1
}
});
That's it! Your first gauge using react-native-fusioncharts
is ready.