ReactNative Fusionchart license configuration not working - javascript

I try to configure the license of Fusionchart in ReactNative as in this URL https://www.npmjs.com/package/react-native-fusioncharts#license-configuration.
But still, it shows the watermark which should not be visible. Is there anything I missed?
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, Platform } from 'react-native';
import ReactNativeFusionCharts from 'react-native-fusioncharts';
global.licenseConfig = {
key: "license-key",
creditLabel: false // true/false to show/hide watermark respectively
};
export default class App extends Component {
constructor(props) {
super(props);
//STEP 2 - Chart Data
const chartData = [
{ label: 'Venezuela', value: '250' },
{ label: 'Saudi', value: '260' },
{ label: 'Canada', value: '180' },
{ label: 'Iran', value: '140' },
{ label: 'Russia', value: '115' },
{ label: 'UAE', value: '100' },
{ label: 'US', value: '30' },
{ label: 'China', value: '30' },
];
//STEP 3 - Chart Configurations
const chartConfig = {
type: 'column2d',
width: 400,
height: 400,
dataFormat: 'json',
dataSource: {
chart: {
caption: 'Countries With Most Oil Reserves [2017-18]',
subCaption: 'In MMbbl = One Million barrels',
xAxisName: 'Country',
yAxisName: 'Reserves (MMbbl)',
numberSuffix: 'K',
theme: 'fusion',
exportEnabled: 1, // to enable the export chart functionality
},
data: chartData,
},
};
const events = {
// Add your events method here:
// Event name should be in small letters.
dataPlotClick: (ev, props) => {
console.log('dataPlotClick');
},
dataLabelClick: (ev, props) => {
console.log('dataLabelClick');
},
};
this.state = {
chartConfig,
events
};
}
render() {
return (
<View style={styles.container}>
<Text style={styles.heading}>FusionCharts Integration with React Native</Text>
<View style={styles.chartContainer}>
<ReactNativeFusionCharts chartConfig={this.state.chartConfig} events={this.state.events} />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 50,
height: 500,
backgroundColor: 'white'
},
heading: {
fontSize: 20,
textAlign: 'center',
marginBottom: 10,
},
chartContainer: {
borderColor: 'red',
borderWidth: 1,
height: 500,
},
});
// skip this line if using Create React Native App
AppRegistry.registerComponent('ReactNativeFusionCharts', () => App);
I also add the below code in the root component but not worked.
global.licenseConfig = {
key: "license-key",
creditLabel: false // true/false to show/hide watermark respectively
};

Answering my own question. Hope this will be helpful to someone.
Issue is latest react-native-fusionchart 5.0.0 is not updated with fusionchart 3.17.0. You may need to manually copy the fusionchart content to react-native-fusionchart.
Copy the node_module/fusionchart content into node_modules/react-native-fusioncharts/src/modules/fusionchart folder and run below script.
find fusioncharts -name "*.js" -exec sh -c 'mv "$0" "${0%.js}.fcscript"' {} \;
Then the watermark vanishes as expected. These steps are configured in the gulp script but somehow it seems to be not working.
Hope this issue will be fixed soon.

Related

Pushing into an array object in react but not rendering on the screen

Im using react and displaying some labels via the array object of labels. Now, I want to do this dynamically. So if a user clicks a button, the object updates and the user interface should update accordingly as well. The issue here is that I got the array to update after clicking on the button, as evidenced by a console log line that I wrote in the onclick handler. But the user interface does not update accordingly. Just the array shows the values. Here is what the inital array looks like:
const labelsArray = [
{ label: 'Hey There', sublabel1: 'How are you?' },
{
label: 'Greetings', sublabel1: 'Fellows'
},
{ label: 'Awesome', sublabel1: 'Youre doing great', sublabel2: 'cool' }
];
I want to append a warningLabel, and errorLabel to the 2nd object of this array. So since arrays are 0 indexed, I did the following in the onclick handler:
const appendLabel = async () => {
labelsArray[1].warningLabel = "Hello";
labelsArray[1].errorLabel = "Hello";
console.log(labelsArray)
};
The array updates, but not the user interface. Which is really weird.
Also, this is not related to react state mutation, which I know because of my research of this topic when I was trying to figure it out. So just to be clear, its not about state mutation, which might have someone put this as a duplicate question. Its more of a react/object structure question. But I could be wrong! Anyways, any help is appreciated. Thanks!
Here is my whole component for reference
import React, { useState } from 'react';
import { Button, Typography } from '#material-ui/core';
import { withStyles } from '#material-ui/core/styles/';
import Stepper from '#material-ui/core/Stepper';
import Step from '#material-ui/core/Step';
import StepLabel from '#material-ui/core/StepLabel';
import StepConnector from '#material-ui/core/StepConnector';
import PropTypes from 'prop-types';
const styles = theme => ({
stepLabelRoot: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
},
checklistHeader: {
fontWeight: 'bold',
marginTop: '80px'
},
connectorIcon: {
color: theme.palette.text.secondary
},
stepper: {
background: 'none',
fontWeight: 'bold'
},
checkListImageContainer: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center'
},
connector: {
},
activeConnector: {
border: 'solid 1px #6fef71'
},
stepIcon: {
height: '35px',
width: '35px',
'&:hover': {
backgroundColor: 'rgba(134, 141, 150, 0.37)',
borderRadius: '50%'
},
},
activeStepIcon: {
backgroundColor: 'yellow'
},
label: {
fontWeight: 'bold',
display: 'flex',
fontSize: '15px'
},
sublabel: {
fontWeight: 'normal',
fontSize: '13px'
},
errorLabel: {
color: 'red'
},
warningLabel: {
color: 'yellow'
},
step: {
'&$completed': {
color: 'lightgreen'
},
'&$active': {
color: 'pink'
},
'&$disabled': {
color: 'red'
},
},
alternativeLabel: {},
active: {
}, // needed so that the &$active tag works
completed: {
},
disabled: {
},
labelContainer: {
'&$alternativeLabel': {
marginTop: 0
},
},
});
const labelsArray = [
{ label: 'Random text?', sublabel1: 'Lorem Ipsum' },
{
label: 'Another random text', sublabel1: 'Hello World'
},
{ label: 'Cool', sublabel1: 'cool', sublabel2: 'ayo' }
];
const Checklist = ({ classes,activeStep }) => {
return (
<React.Fragment>
<Stepper alternativeLabel activeStep={2} connector={<StepConnector />} className={classes.stepper}>
{labelsArray.map(label => (
<Step key={label} completed>
<StepLabel active
completed
StepIconProps={{
classes: {
root: classes.step,
completed: classes.completed,
active: classes.active,
disabled: classes.disabled
}
}}>
<div className={classes.stepLabelRoot}>
<span className={classes.label}>
{label.label}
</span>
<span className={classes.sublabel}>
{label.sublabel1}
</span>
<span className={classes.sublabel}>
{label.sublabel2}
</span>
<span className={classes.sublabel}>
{label.sublabel3}
</span>
<span className={classes.errorLabel}>
{label.errorLabel && <img src="/static/images/lock-material.png" alt="img" style={{ height: '15px', width: '15px' }} />}
{label.errorLabel}
</span>
<span className={classes.warningLabel}>
{label.warningLabel && <img src="/static/images/warning-sign.png" alt="img" style={{ height: '15px', width: '15px' }} />}
{label.warningLabel}
</span>
</div>
</StepLabel>
</Step>
))}
</Stepper>
<Button onClick={() => appendLabel()}>Hello</Button>
</React.Fragment>
);
};
Checklist.defaultProps = {
activeStep: -1
};
Checklist.propTypes = {
classes: PropTypes.object.isRequired,
form: PropTypes.bool.isRequired,
activeStep: PropTypes.number
};
export default withStyles(styles, { withTheme: true })(Checklist);
You need to set the labelsArray in the state and update it accordingly in order to re-render the component when the user clicks the button
Edited:
A way of doing that with a state would be:
const LABELS =[
{ label: 'Hey There', sublabel1: 'How are you?' },
{ label: 'Greetings', sublabel1: 'Fellows' },
{ label: 'Awesome', sublabel1: 'Youre doing great', sublabel2: 'cool' }
];
const [labelsArray, setLabelsArray] = useState(LABELS);
const appendLabel = () => {
let editedLabels = [...labelsArray];
editedLabels[1].warningLabel = "Hello";
editedLabels[1].errorLabel = "Hello";
setLabelsArray(editedLabels);
};

Printing a list by clicking chart Chart js + react

Hi i'm having troubles printing in a alert (by clicking one of the portions), a list of users for a specific answer in chart.js + react here's my chart component
Piechart.js
import React,{ Component } from 'react';
import {Chart} from 'react-chartjs-2';
class Piechart extends Component {
constructor(props){
super(props)
this.chartReference = React.createRef();
this.state = {
data:[]
};
}
async componentDidMount(){
const url = "https://api-tesis-marco.herokuapp.com/api/v1/questiondata/"+this.props.title;
const data = await fetch(url)
.then(response => response.json());
this.setState({data:data});
this.myChart = new Chart(this.chartReference.current,{
type: 'pie',
data:{
labels: this.state.data.map(d=>d.Respuesta),
datasets: [{
data: this.state.data.map(d=>d.porcentaje),
backgroundColor: this.props.colors
}],
},
options: {
title: {
display: true,
text: this.props.title,
fontSize: 20,
fontStyle: 'bold'
},
legend: {
position:'right'
},
onClick: clicked
}
});
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
alert();
}
}
}
render(){
return(
<canvas ref={this.chartReference} />
)
}
}
export default Piechart;
//i having troubles passing the lists data of my request
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
//i don't know what to do here
alert();
}
}
Here is the json response of my request:
Data:
[
{
"Respuesta": "A",
"porcentaje": 7,
"quien": [
"1",
"visita1"
]
},
{
"Respuesta": "B",
"porcentaje": 3,
"quien": [
"coco"
]
},
{
"Respuesta": "C",
"porcentaje": 3,
"quien": [
"Dani3l"
]
},
{
"Respuesta": "D",
"porcentaje": 10,
"quien": [
"Gabi",
"test",
"visita prueba"
]
},
{
"Respuesta": "No ha respondido",
"porcentaje": 76,
"quien": [
"9punto5",
"Colita de algodón",
"KarmenQueen",
"Prueba",
"ancova",
"cehum2",
"chuky",
"dev",
"felipe",
"gabs",
"icom2019",
"invunche",
"john",
"laura",
"marian",
"marti",
"pablazozka",
"prueba",
"test1",
"titicaco",
"visita 1",
"visita test"
]
}
]
in my clicked function how can i pass the "quien" lists for the specific portion of my pie chart?, so in the alert i can print the list of that portion , i'm using this as guide https://jsfiddle.net/u1szh96g/208/ but is difficult for me adapt this to react
well after some mixed tutorials and guides, i came with the solution
Piechart.js:
import React,{ Component } from 'react';
import {Chart} from 'react-chartjs-2';
class Piechart extends Component {
constructor(props){
super(props)
this.chartReference = React.createRef();
this.state = {
data:[]
};
}
async componentDidMount(){
const url = "https://api-tesis-marco.herokuapp.com/api/v1/questiondata/"+this.props.title;
const data = await fetch(url)
.then(response => response.json());
this.setState({data:data});
var datasets = [{data: this.state.data.map(d=>d.Count),
backgroundColor: this.props.colors
},
{
data: this.state.data.map(d=>d.Percent)
},
{
data: this.state.data.map(d=>d.Who)}]
this.myChart = new Chart(this.chartReference.current,{
type: 'pie',
data:{
labels: this.state.data.map(d=>d.Answer),
datasets: [{
data: datasets[0].data,
backgroundColor: datasets[0].backgroundColor
}]
},
options: {
title: {
display: true,
text: this.props.title,
fontSize: 20,
fontStyle: 'bold'
},
legend: {
position:'right'
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return 'Respuesta:'+data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'Total:'+data['datasets'][0]['data'][tooltipItem['index']];
},
afterLabel: function(tooltipItem) {
var dataset = datasets[1];
var total = dataset['data'][tooltipItem['index']]
return '(' + total+ '%)';
}
},
backgroundColor: '#FFF',
titleFontSize: 16,
titleFontColor: '#0066ff',
bodyFontColor: '#000',
bodyFontSize: 14,
displayColors: false
},
onClick: clicked
}
});
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
var idx = element[0]['_index'];
var who = datasets[2].data[idx];
alert(who);
}
}
}
render(){
return(
<canvas ref={this.chartReference} />
)
}
}
export default Piechart;
as you can see i only set an datasets array outside
var datasets = [{
data: this.state.data.map(d=>d.Count),
backgroundColor: this.props.colors
},
{
data: this.state.data.map(d=>d.Percent)
},
{
data: this.state.data.map(d=>d.Who)}]
this contains all the datasets of the request, then in the chart instance i only pass the dataset i want to plot, then for my question, in the clicked function only call the element of the array wich contains the list of users for the specific answer
Cliked function:
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
var idx = element[0]['_index'];
var who = datasets[2].data[idx];
alert(who);
}
}
i made a custom tooltip as well, but i have an issue with this(with the default tooltip is the same) because i use this component to plot 4 piecharts but when i hover the mouse only 2 of the 4 charts show me the tooltip, the 2 chart who shows the tooltip are random (when refresh localhost pick randomly 2 of the 4 charts), and i don't know what is happend or how to fix this, i hope this is usefull to someone

Nivo bar chart calling label function hundreds of times

I'm using Nivo bar to represent a user's progress on a budget. I've normalized the data by dividing the category balance by the category goal. Example data.
[{
"category": "Gas",
"budget": 0.24,
"over_budget": 0.0
},
{
"category": "Groceries",
"budget": 1.0,
"over_budget": 0.26
}]
I don't want these values to be used as the label on the chart. I plan to use the actual balance value as the label. I have an endpoint that will return the balance for a category and have attempted the following to use that value:
<ResponsiveBar
...
label={d => this.getDollarAmount(d.value)}
...
>
With the function POC as:
getDollarAmount(value) {
console.log("hitting getDollarAmount")
return 1
};
The log message gets logged 500+ times. My expectation would be that the function would only be hit once for each bar in the chart.
I'm still learning react so this could be something obvious. Thanks in advance!
EDIT - Here's the entire BarChart component:
import axios from 'axios';
import React, { Component } from "react";
import { ResponsiveBar } from '#nivo/bar'
// Nivo theming
const theme = {
axis: {
ticks: {
line: {
stroke: "#e9ecee",
strokeWidth: 40
},
text: {
// fill: "#919eab",
fill: "black",
fontFamily: "BlinkMacSystemFont",
fontSize: 16
}
}
},
grid: {
line: {
stroke: "#e9ecee",
strokeWidth: 5
}
},
legends: {
text: {
fontFamily: "BlinkMacSystemFont"
}
}
};
let budgetStatusAPI = 'http://127.0.0.1:8000/api/budget_status/?auth_user=1&month=2020-02-01';
class BarChart extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
this.getDollarAmount = this.getDollarAmount.bind(this);
}
componentDidMount() {
console.log("component did mount")
axios.get(budgetStatusAPI).then(response => {
this.setState({
data: response.data
}, function () {
console.log(this.state.data);
})
});
}
componentDidUpdate() {
console.log("component did update")
}
getDollarAmount(value) {
console.log("hitting getDollarAmount")
console.log(value)
return 1
};
render() {
const hard_data = [
{
"category": "Groceries",
"budget_status": 1.0,
"over_budget": .26,
},
{
"category": "Gas",
"budget_status": .24,
"over_budget": 0.0,
}]
return(
<ResponsiveBar
maxValue={1.5}
markers={[
{
axis: 'x',
value: 1,
lineStyle: { stroke: 'rgba(0, 0, 0, .35)', strokeWidth: 2 },
legend: 'Goal',
legendOrientation: 'horizontal',
legendPosition: 'top'
},
]}
enableGridX={false}
gridXValues={[1]}
enableGridY={false}
data={this.state.data}
// data={hard_data}
keys={['budget_status', 'over_budget']}
indexBy="category"
margin={{ top: 25, right: 130, bottom: 50, left: 125 }}
padding={0.3}
layout="horizontal"
colors={{ scheme: 'set2' }}
theme={theme}
defs={[
{
id: 'dots',
type: 'patternDots',
background: 'inherit',
color: '#38bcb2',
size: 4,
padding: 1,
stagger: true
},
{
id: 'lines',
type: 'patternLines',
background: 'inherit',
color: '#eed312',
rotation: -45,
lineWidth: 6,
spacing: 10
}
]}
borderColor={{ from: 'color', modifiers: [ [ 'darker', 1.6 ] ] }}
axisBottom={null}
label={d => this.getDollarAmount(d.value)}
isInteractive={false}
animate={true}
motionStiffness={90}
motionDamping={15}
/>
)
}
}
export default BarChart;
Reproduced here: https://codesandbox.io/s/nivo-bar-label-issue-k4qek
The multiple calling is happening because the bar chart is calling label function for each animation tick/frame render. If we setup a counter, we'll see with animate prop set to true it will render from 450+ to 550+ times, but if we set the prop animate to false, we'll it renders 6 times which is exactly how many price values are > 0.0.
If you want to avoid all these renders, you'll have to disable animation using animate={false} prop like this:
getDollarAmount(value) {
// Remove every console.log inside this function
return `$${value}`
}
render() {
return (
<ResponsiveBar
animate={false}
label={d => this.getDollarAmount(d.value)}
...
);
}
You can check it running to your cloned CodeSandbox. I have set animate to false and the counter log inside getDollarAmount is calling 6 times. Try to change animate to true and you'll see the 500+- renders.
Also, you don't have to create a function for each label call, you can just pass the getDollarAmount function and let it handle the whole d parameter like this:
getDollarAmount(d) {
// Remove every console.log inside this function
return `$${d.value}`
}
render() {
return (
<ResponsiveBar
animate={false}
label={this.getDollarAmount}
...
);
}

How do I update only one trace in react plotly?

I am using react-plotly to generate a large timeline of data (10,000-100,000 points) and I animate across the data in another window. I need to get a scrubber (vertical line) that moves with a react-property representing time, but I need to update the scrubber without updating the rest of the timeline, since it would take so long to do so. How can I get just the vertical line to update?
Edit: Was asked for code
In the following code, the backtracks and thresholds objects are Uint32Arrays and represent the y-axis of traces, where the x-axes are the Uint32Arrays backtracksTime and thresholdsTime. What I am trying to get is a vertical line at the x-coordinate currentTime.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Plotly from 'plotly.js';
import Plot from 'react-plotly.js';
import styles from './style.scss';
export default class ThresholdWindow extends Component {
static propTypes = {
name: PropTypes.string,
backtracks: PropTypes.object,
backtracksTime: PropTypes.object,
thresholds: PropTypes.object,
thresholdsTime: PropTypes.object,
currentTime: PropTypes.number,
}
constructor(props) {
super(props);
this.state = {
plotRevision: 0,
width: 0,
height: 0,
};
}
componentDidMount() {
const resizeObserver = new ResizeObserver(entries => {
const oldPlotRevision = this.state.plotRevision;
const rect = entries[0].contentRect;
this.setState({
plotRevision: oldPlotRevision + 1,
height: rect.height,
width: rect.width,
});
});
resizeObserver.observe(this.container);
}
shouldComponentUpdate(nextProps, nextState) {
if (this.state.plotRevision !== nextState.plotRevision) {
return true;
} else if (this.props.currentTime !== nextProps.currentTime) {
return true;
}
return false;
}
render() {
const data = [
{
name: 'Threshold',
type: 'scattergl',
mode: 'lines',
x: this.props.thresholdsTime,
y: this.props.thresholds,
side: 'above',
},
{
name: 'Backtracks',
type: 'scattergl',
mode: 'lines',
x: this.props.backtracksTime,
y: this.props.backtracks,
},
{
name: 'Current Time',
type: 'scattergl',
mode: 'lines',
x: [this.props.currentTime, this.props.currentTime],
y: [0, 1],
yaxis: 'y2',
},
];
return (
<div className={styles['threshold-window']} ref={(el) => { this.container = el; }}>
<Plot
divId={`backtracks-${this.props.name}`}
className={styles['threshold-graph']}
ref={(el) => { this.plot = el; }}
layout={{
width: this.state.width,
height: this.state.height,
yaxis: {
fixedrange: true,
},
yaxis2: {
side: 'right',
range: [0, 1],
},
margin: {
l: 35,
r: 15,
b: 20,
t: 15,
},
legend: {
orientation: 'h',
y: 1,
},
}}
revision={this.state.plotRevision}
data={data}
/>
</div>
);
}
}
Edit2: I don't actually see the currentTime line anywhere, so I'm pretty sure there's a bug somewhere.
With react-plotly.js the performance should be decent, as it will only redraw what it needs to.

React Native button map for a button group

Trying to figure out how to change the styling on just the first and last button. How do I tell the button which one is which? Beginner in JS and React/React Native trying to find my way. Currently coming out with no rounded buttons on either end. The Button element in the child is my own wrapper on TouchableOpacity and only accepts an object for the buttonStyles. Any help appreciated.
Parent component:
export class Rating extends React.Component {
ratings = [
{ text: '1' },
{ text: '2' },
{ text: '3' },
{ text: '4' },
{ text: '5' },
];
onButtonPress = (e) => {
console.log(e.target.value);
};
render() {
return (
<View>
{this.ratings.length && (
this.ratings.map((rating, index) => (
<View key={index}>
<RatingButton rating={rating} onButtonPress={this.onButtonPress} />
</View>
))
)
}
</View>
);
}
}
Child component:
const buttonStyles = () => {
const allButtons = {
backgroundColor: sc.colors.white.white,
borderWidth: 1.5,
borderColor: sc.colors.blue.darker1,
padding: sc.padding.lg,
};
const startButton = {
borderTopLeftRadius: sc.borderRadius.sm,
borderBottomLeftRadius: sc.borderRadius.sm,
borderRightWidth: 0.75,
...allButtons,
};
const endButton = {
borderTopRightRadius: sc.borderRadius.sm,
borderBottomRightRadius: sc.borderRadius.sm,
borderLeftWidth: 0.75,
...allButtons,
};
return StyleSheet.create({
allButtons,
startButton,
endButton,
buttonText: {
color: sc.colors.blue.darker1,
fontSize: sc.font.size.largeContent,
},
});
};
class RatingButton extends React.Component {
render() {
const { onButtonPress, rating } = this.props;
const styles = buttonStyles();
return (
<Button
buttonStyles={styles.allButtons}
textStyles={styles.buttonText}
onPress={onButtonPress}
>
{rating.text}
</Button>
);
}
}
Inside of your ratings variable, you could store another attribute for style like so:
ratings = [
{ text: '1', style: {backgroundColor:'red'} },
{ text: '2' },
{ text: '3' },
{ text: '4' },
{ text: '5', backgroundColor: 'yellow' },
];
And then inside of <RatingButton/> you can add the style to the element
<Button
buttonStyles={styles.allButtons}
textStyles={styles.buttonText}
onPress={onButtonPress}
style={rating.style}
>
{rating.text}
</Button>
Note: You could also pass a class through the rating variable.
ratings = [
{ text: '1', buttonStyle: 'startButton' },
{ text: '2' },
{ text: '3' },
{ text: '4' },
{ text: '5', buttonStyle: 'endButton' },
];
and set your style like this:
<Button
buttonStyles={ratings.buttonStyle?styles[rating.buttonStyle]:styles.allButtons}
textStyles={styles.buttonText}
onPress={onButtonPress}
style={rating.style}
>
{rating.text}
</Button>

Categories

Resources