Related
I have a html file with script tag and some link into it.
when i render it with html file it bring the result i mean a chart but when i render it in react js app wiht dangerouslySetInnerHTML it does not render and does not bring my chart.
this is my html code that i take it from backend(api)
const html = `<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0" />
<link
href="somelink"
rel="stylesheet"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="app-chart-container">
<canvas class="app-charts" id="line-chart-40197" dir="ltr"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script>
$(document).ready(function () {
$("[data-toggle='tooltip']").tooltip({ placement: "right" });
});
var ctx = document.getElementById("line-chart-40197");
if (ctx) {
ctx.height = 300;
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: [
"92/3",
"92/6",
"92/9",
"92/12",
"93/3",
"93/6",
"93/9",
"93/12",
"94/3",
"94/6",
"94/9",
"94/12",
"95/3",
"95/6",
"95/9",
"95/12",
"96/3",
"96/6",
"96/9",
"96/12",
"97/3",
"97/6",
"97/9",
"97/12",
"98/3",
"98/6",
"98/9",
"98/12",
"99/3",
"99/6",
],
type: "line",
defaultFontFamily: "VazirFD",
datasets: [
{
label: "شرکت",
data: [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"-262",
"-262",
"-262",
"-262",
"66793",
"70787",
"122463",
"591087",
"591088",
"597421",
"600635",
"614257",
"1304086",
"1320727",
"1352606",
"2830629",
"3016812",
"3042351",
"3126253",
],
backgroundColor: "transparent",
borderColor: "#9d0606",
borderWidth: 2,
pointStyle: "circle",
pointRadius: 3,
pointBorderColor: "transparent",
pointBackgroundColor: "#9d0606",
type: "line",
},
],
},
options: {
responsive: true,
tooltips: {
mode: "index",
titleFontSize: 12,
titleFontColor: "#000",
bodyFontColor: "#000",
backgroundColor: "#fff",
defaultFontFamily: "VazirFD",
titleFontFamily: "VazirFD",
bodyFontFamily: "VazirFD",
cornerRadius: 3,
intersect: true,
callbacks: {
label: function (tooltipItem, data) {
return (
data.datasets[tooltipItem.datasetIndex].label +
" : " +
tooltipItem.yLabel
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
);
},
},
},
legend: {
display: true,
rtl: true,
labels: {
usePointStyle: true,
fontFamily: "VazirFD",
},
},
scales: {
xAxes: [
{
stacked: false,
display: true,
gridLines: {
display: true,
drawBorder: false,
},
scaleLabel: {
display: true,
labelString: "سال مالی",
fontFamily: "VazirFD",
},
ticks: {
fontFamily: "VazirFD",
fontColor: "#9aa0ac",
minRotation: 90,
callback: function (value, index, values) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
},
},
],
yAxes: [
{
stacked: false,
display: true,
gridLines: {
display: true,
drawBorder: false,
},
scaleLabel: {
display: false,
labelString: "میلیون ریال",
fontFamily: "VazirFD",
},
ticks: {
margin: 20,
fontFamily: "VazirFD",
fontColor: "#9aa0ac",
minRotation: 0,
callback: function (value, index, values) {
var processValue = value;
if (value >= 1000 && value < 1000000) {
processValue = value / 1e3 + "K";
} else if (value >= 1000000 && value < 1000000000) {
processValue = value / 1e6 + "M";
} else if (value >= 1000000000) {
processValue = value / 1e9 + "B";
} else if (value < 0 && value <= -1000 && value > -1000000) {
processValue = value / 1e3 + "K";
} else if (
value < 0 &&
value <= -1000000 &&
value > -1000000000
) {
processValue = value / 1e6 + "M";
} else if (value < 0 && value <= -1000000000) {
processValue = value / 1e9 + "B";
}
return processValue
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
},
},
],
},
title: {
display: true,
text: "روند سودآوری TTM (میلیون ریال)",
fontFamily: "VazirFD",
},
},
});
}
</script>
this is my html file.
but i have a problem with render of that with react
when I compile this file with
this is my react component that i want to render that html code (my html code has some script tag )
import React from "react";
export default function Dashboard() {
return (
<div dangerouslySetInnerHTML={{__html: html }} />
)
}
i dont get my html file correctly.
and react does not render it.
when i open this file into .html file it works but in react does not render any thing.
how can i render this file in react please help me
I had to do this recently because an API I was consuming returns HTML content. You can use a library like html-to-react to parse the HTML for you and convert it to a React component that you can then use inside your React application. In my case, I created a component so that I can reuse this logic anywhere I need to display HTML content.
import { useMemo } from 'react';
import { Parser } from 'html-to-react';
const HTMLContent = (props) => {
const htmlToReactParser = useMemo(() => new Parser(), []);
const parsedHTML = htmlToReactParser.parse(props.html);
return <div className={styles['blog-html-content']}>{parsedHTML}</div>;
};
I have a response json like this:
{
"variables": {
"lock": 0,
"pos": 55,
"pos_on": 55,
"pos_off": 150
},
"id": "11",
"name": "Lock_table_2",
"hardware": "esp8266",
"connected": true
}
and I try to show the lock value in 'variables' object
so I write
constructor(props) {
super(props)
this.state = {
dock_1: {}, // define a empty json
dock_2: {},
dock_3: {},
}
}
pingIP() {
axios
.get('http://192.168.50.225:8888/test_check')
.then(response => {
let data = response.data.list; // return value is a list
this.setState({ // every 2 sec setState
dock_1: data[0], // data[0] -> 192.168.50.40's json
dock_2: data[1],
dock_3: data[2],
})
})
}
render(){
return (
<p>{this.state.dock_1.variables.lock}</p>
);
}
but I got this error
in here
So I tried this
render(){
return (
<p>{this.state.dock_1.variables}</p>
);
}
then here comes the another error message
in here
here is the get request return value
{
"list": [
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_1",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_2",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_3",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
}
]
}
the return value is a list
in order to get first value so I wrote data[0], data1 ...
what's happening in here?
I think your response is an array of 3 items like this:
[
{
variables: {
lock: 0,
pos: 55,
pos_on: 55,
pos_off: 150
},
id: "11",
name: "Lock_table_2",
hardware: "esp8266",
connected: true
},
{
variables: {
lock: 1,
pos: 44,
pos_on: 56,
pos_off: 151
},
id: "11",
name: "Lock_table_3",
hardware: "esp8267",
connected: false
},
{
variables: {
lock: 2,
pos: 45,
pos_on: 57,
pos_off: 152
},
id: "11",
name: "Lock_table_4",
hardware: "esp8268",
connected: true
}
]
So you can access the dock 1 variable lock using Inline If with Logical && Operator to prevent null exception.
<p>{this.state.dock_1.variables && this.state.dock_1.variables.lock}</p>
A sample working codesandbox with a fake api:
https://codesandbox.io/s/stoic-chaplygin-r1yxd
The last series in a bar chart is showing "Series 4" as a name, even though its proper name is coming correcty from json file.
The information from the json file comes from a SQL query that prints the information in a string with the following format:
[
{"name": "Operation","data": [{"y":3000, "second": 1500, "third": 5}]},
{"name": "Mechanical","data": [{"y":2515, "second": 515, "third": 8}]},
{"name": "Electrical","data": [{"y":1800, "second": 475, "third": 10}]},
{"name": "Operation Slag","data": [{"y":1000, "second": 1500, "third": 7}]}
]
Since the colors of the series are set manually, I am using the below to add just data and name to each series:
jspData.forEach(function(jspData, i) {
Delays.series[i].setData(jspData.data);
Delays.series[i].setName(jspData.name);
}];
This is working as expected until the last series which show "Series 4" name and not "Operation Slag".
$(function () {
$(document).ready(function(){
$.getJSON('getData.json', function(jspData) {
var Delays = new Highcharts.chart({
chart: {
renderTo: 'Delays',
type: 'bar'
},
xAxis: {
categories: [''],
lineWidth: 0,
minorTickLength: 0,
tickLength: 0,
gridLineWidth: 0,
minorGridLineWidth: 0,
title: {
text: null
}
},
yAxis: {
gridLineWidth: 0,
minorGridLineWidth: 0,
lineWidth: 0,
tickWidth: 0,
tickLength: 0,
min: 0,
title: null,
labels: {
enabled: false,
}
},
tooltip: {
enabled:true,
style:{fontSize:'10px', fontFamily:"sans-serif"},
formatter: function() {
console.log(this);
return 'Total duration: ' + this.y + 'min<br/>Delay Code: ' + this.point.second + '<br/>Count of Events: ' + this.point.third;
},
},
plotOptions: {
bar: {
borderWidth: 0.5,
dataLabels: {
enabled: true,
format: '{series.name}',
style: {
fontSize: "10px",
fontWeight:'normal',
textOutline: false,
fontFamily: 'sans-serif',
},
}
},
series: {
groupPadding: 0,
pointPadding: 0,
},
},
legend:{
enabled:false,
},
series: [{
color:'#4572A7',
data: []
}, {
color:'#89A54E',
data: []
}, {
color:'#AA4643',
data: []
}, {
color:'#A1745B',
data: []
}],
});
jspData.forEach(function(jspData, i) {
Delays.series[i].setData(jspData.data);
Delays.series[i].setName(jspData.name);
});
});
});
});
Last series name should not be "Series 4" but "Operation Slag". Chart is render porperly all other data is populated correctly.
The setName method is internal and it requires to redraw the chart. In your case it's enough to change the order of calls, because setData causes redraw:
jspData.forEach(function(jspData, i) {
Delays.series[i].setName(jspData.name);
Delays.series[i].setData(jspData.data);
});
Live demo: http://jsfiddle.net/BlackLabel/0qkf26zp/
API: https://api.highcharts.com/class-reference/Highcharts.Series#setData
I know you can animate circles on google maps , see example
http://jsbin.com/nuwem/1/edit?html,output
.....But can you do the same thing on Mapbox
I am creating a live earthquake map www.livehazards.com. Each earthquake mag is respresent by a circle
I would just like the outline of the circle and to be able to animate it.
I have tried using circle-stroke for just the outline but it did not work
Thanks
To animate your circle you can simply change its paint property several times: map.setPaintProperty('yourmarker', 'circle-radius', 20)
If you only want the circle outline, set "circle-opacity":0 and "circle-stroke-width": 1.
Codepen
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [ 2.35, 48.85 ],
zoom: 3
});
map.on('load', () => {
let radius = 1;
map.addLayer({
"id": "points",
"type": "circle",
// Create the marker
"source": {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ 2.35, 48.85 ]
}
}]
}
},
// Draw the circle
"paint": {
"circle-opacity": 0,
"circle-stroke-width": 1,
"circle-stroke-color": "#000",
"circle-radius": radius,
"circle-radius-transition": {
"duration": 0
}
}
});
// Animate the circle
setInterval(() => {
map.setPaintProperty('points', 'circle-radius', radius);
radius = ++radius % 30;
}, 50);
});
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [ 2.35, 48.85 ],
zoom: 3
});
map.on('load', function() {
let radius = 1;
map.addSource("earthquakes", {
type: "geojson",
data: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson",
});
map.addLayer({
"id": "earthquake-layer",
"type": "circle",
"source": "earthquakes",
"paint": {
"circle-opacity": 0.4,
"circle-color": "#830300",
"circle-stroke-width": 2,
"circle-stroke-color": "#fff",
"circle-radius": {
"property": "mag",
"base": 2.5,
"stops": [
[{zoom: 0, value: 2}, 1],
[{zoom: 0, value: 8}, 40],
[{zoom: 11, value: 2}, 10],
[{zoom: 11, value: 8}, 2400],
[{zoom: 20, value: 2}, 20],
[{zoom: 20, value: 8}, 6000]
"circle-radius-transition": {
"duration": 0
}
]
}
}
});
setInterval(() => {
map.setPaintProperty('eaarthquake-layer', 'circle-radius', radius);
radius = ++radius % 30
}, 50);
});
Context
I want to use cytoscape.js for visualizing graphs. While I am capable with a myriad of languages (C++, Mathematica, R, etc), I am new to Javascript, JSON, HTML, and CSS. Thus it would be favorable to learn these languages through this use case (implementing graphs with cytoscape.js). Please keep this in mind in your answer.
I have previously asked how to [remotely load cytoscape.js and how to get graphs display (requires a div). Since then I have created a script that turns a graph as represented in one of the other languages I use, into the JSON format indicated here. While I can just copy-paste all of this directly into my program, for large networks that is clearly a poor way to implement it. An example of my script's output is at the bottom of this.
Question
Given a JSON object/file(?) how can I do the following:
load it into cytoscape.js without copy-pasting the code.
referencing it once loaded. (e.g. basic explanation of how JSON syntax for use in cytoscape.js)
Script Output
cytoscape({
container: document.getElementById('cy'),
elements: [
{// node Node 1
group: 'nodes',
data: {
id: 'Node 1'
},
selected: false,
selectable: true,
locked: false,
grabbable: true,
selectable: true,
},
{// node Node 2
group: 'nodes',
data: {
id: 'Node 2'
},
selected: false,
selectable: true,
locked: false,
grabbable: true,
selectable: true,
},
{// node Node 3
group: 'nodes',
data: {
id: 'Node 3'
},
selected: false,
selectable: true,
locked: false,
grabbable: true,
selectable: true,
},
{// edge 1_2
group: 'edges',
data: {
id: '1_2',
source: '1',
target: '2'
}
},
{// edge 2_3
group: 'edges',
data: {
id: '2_3',
source: '2',
target: '3'
}
},
{// edge 3_1
group: 'edges',
data: {
id: '3_1',
source: '3',
target: '1'
}
}
],
style: [
{
selector: 'node',
style: {
'content': 'data(id)'
}
}
]
});
<head>
<title></title>
<script src="js/vendor/cytoscape.min.js"></script>
<script src="js/vendor/jquery.min.js"></script>
</head>
<style>
#cy {
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
</style>
<body>
<div id="cy"></div>
<script>
$.getJSON("cyto.js", function (data) {
//console.log(data);
var cy = cytoscape({
container: document.getElementById('cy'),
elements: data,
style: [
{
selector: 'node',
style: {
'label': 'data(label)',
'width': '60px',
'height': '60px',
'color': 'blue',
'background-fit': 'contain',
'background-clip': 'none'
}
}, {
selector: 'edge',
style: {
'text-background-color': 'yellow',
'text-background-opacity': 0.4,
'width': '6px',
'target-arrow-shape': 'triangle',
'control-point-step-size': '140px'
}
}
],
layout: {
name: 'circle'
}
});
});
</script>
</body>
in cyto.js you can input valid JSON data, for example
{
"nodes": [
{
"data": {"id": "a", "label": "Gene1"}
},
{
"data": {"id": "b", "label": "Gene2"}
},
{
"data": {"id": "c", "label": "Gene3"}
},
{
"data": {"id": "d", "label": "Gene4"}
},
{
"data": {"id": "e", "label": "Gene5"}
},
{
"data": {"id": "f", "label": "Gene6"}
}
],
"edges": [
{
"data": {
"id": "ab",
"source": "a",
"target": "b"
}
},
{
"data": {
"id": "cd",
"source": "c",
"target": "d"
}
},
{
"data": {
"id": "ef",
"source": "e",
"target": "f"
}
},
{
"data": {
"id": "ac",
"source": "a",
"target": "d"
}
},
{
"data": {
"id": "be",
"source": "b",
"target": "e"
}
}]
}
Let's presume you have a json file in the same folder as your 'index.html', and your server is running. First request the json file via a http request (using plain javascript or jquery ).
If your json file has the same format as the elements properties, you can just parse it to a javascript object and set it. E.g.
var myObject = {};
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObject = JSON.parse(this.responseText);
initCytoscape();
}
};
xhttp.open("GET", "myJson.json", true);
xhttp.send();
function initCytoscape() {
cytoscape({
container: document.getElementById('cy'),
elements: myObject
});
}
if the json property is different than cytoscape's format, then you have to programatically convert it.