Working with Data in React Stock Chart
Stock Chart can visualizes data bound from local or remote data.
Local Data
You can bind a simple JSON data to the chart using dataSource property in series.
import * as React from "react";
import * as ReactDOM from "react-dom";
import { StockChartComponent, StockChartSeriesCollectionDirective, StockChartSeriesDirective, Inject, DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines } from '@syncfusion/ej2-react-charts';
import { EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator, AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator, Export } from '@syncfusion/ej2-react-charts';
import { chartData } from './datasource';
function App() {
return (<StockChartComponent id='stockchart' primaryXAxis={{
valueType: 'DateTime',
majorGridLines: { width: 0 }, majorTickLines: { color: 'transparent' },
crosshairTooltip: { enable: true }
}} primaryYAxis={{
labelFormat: 'n0',
lineStyle: { width: 0 }, rangePadding: 'None',
majorTickLines: { width: 0 }
}} title='Sales Analysis' bearFillColor='#2ecd71' bullFillColor='#e74c3d' height='350'>
<Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines,
EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator, Export,
AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator]}/>
<StockChartSeriesCollectionDirective>
<StockChartSeriesDirective dataSource={chartData} type='Candle' animation={{ enable: true }}>
</StockChartSeriesDirective>
</StockChartSeriesCollectionDirective>
</StockChartComponent>);
}
;
export default App;
ReactDOM.render(<App />, document.getElementById("charts"));import * as React from "react";
import * as ReactDOM from "react-dom";
import {
StockChartComponent, StockChartSeriesCollectionDirective, StockChartSeriesDirective, Inject, ITooltipRenderEventArgs, IStockChartEventArgs, ChartTheme,
DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines
} from '@syncfusion/ej2-react-charts';
import {
EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator,
AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator, Export
} from '@syncfusion/ej2-react-charts';
import { chartData } from './datasource';
function App() {
return (
<StockChartComponent id='stockchart'
primaryXAxis={{
valueType: 'DateTime',
majorGridLines: { width: 0 }, majorTickLines: { color: 'transparent' },
crosshairTooltip: { enable: true }
}}
primaryYAxis={{
labelFormat: 'n0',
lineStyle: { width: 0 }, rangePadding: 'None',
majorTickLines: { width: 0 }
}}
title= 'Sales Analysis'
bearFillColor='#2ecd71'
bullFillColor='#e74c3d'
height='350'
>
<Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines,
EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator, Export,
AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator]} />
<StockChartSeriesCollectionDirective>
<StockChartSeriesDirective dataSource={chartData} type='Candle' animation={{ enable: true }}>
</StockChartSeriesDirective>
</StockChartSeriesCollectionDirective>
</StockChartComponent>
)
};
export default App;
ReactDOM.render(<App />, document.getElementById("charts"));Handling No Data
When no data is available to render in the stock chart, the noDataTemplate property can be used to display a custom layout within the chart area. This layout may include a message indicating the absence of data, a relevant image, or a button to initiate data loading. Styled text, images, or interactive elements can be incorporated to maintain design consistency and improve user guidance. Once data becomes available, the chart automatically updates to display the appropriate visualization.
import * as React from "react";
import * as ReactDOM from "react-dom";
import { StockChartComponent, StockChartSeriesCollectionDirective, StockChartSeriesDirective, Inject, DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines } from '@syncfusion/ej2-react-charts';
import { EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator, AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator, Export } from '@syncfusion/ej2-react-charts';
import { chartData } from './datasource';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
function App() {
const [hasData, setHasData] = React.useState(false);
var chart;
React.useEffect(() => {
if (hasData) {
const buttonContainer = document.getElementById("syncfusionButtonContainer");
if (buttonContainer) {
ReactDOM.unmountComponentAtNode(buttonContainer);
}
}
}, [hasData]);
const SAMPLE_CSS = `
#noDataTemplateContainer {
height: inherit;
width: inherit;
}
.light-bg {
background-color: #fafafa;
color: #000000;
}
.template-align img {
max-width: 150px;
/* Adjust size as needed */
max-height: 150px;
margin-top: 55px;
}
.load-data-btn {
border-radius: 4px;
}
.template-align {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
flex-direction: column;
}
#syncfusionButtonContainer {
margin-top: 5px;
}`;
const noDataTemplate = `
<div id="noDataTemplateContainer" class="light-bg">
<div class="template-align">
<img src="no-data.png" alt="No Data"/>
</div>
<div class="template-align">
<p style="font-size: 15px; margin: 10px 0 10px;"><strong>No data available to display.</strong></p>
</div>
<div class="template-align">
<div id="syncfusionButtonContainer"></div>
</div>
</div>
`;
// Function to load data when button is clicked
const loadData = () => {
if (chart) {
chart.series[0].dataSource = chartData;
}
};
// Function to load data when button is clicked
const loadedChartData = () => {
if (!hasData) {
const buttonContainer = document.getElementById("syncfusionButtonContainer");
if (buttonContainer && !buttonContainer.hasChildNodes()) {
// Create the button element using React.createElement
const buttonElement = React.createElement(ButtonComponent, {
id: "loadDataButton",
content: "Load Data",
iconCss: "e-icons e-refresh",
cssClass: "load-data-btn e-outline",
isPrimary: false,
onClick: loadData
});
ReactDOM.render(buttonElement, buttonContainer);
}
}
};
return (
<div>
{/* Custom No Data Template with Button */}
<style>{SAMPLE_CSS}</style>
{/* Chart Component */}
<div id="chart-container">
<StockChartComponent id='stockchart' ref={g => chart = g} loaded={loadedChartData} noDataTemplate={noDataTemplate} primaryXAxis={{
valueType: 'DateTime',
majorGridLines: { width: 0 }, majorTickLines: { color: 'transparent' },
crosshairTooltip: { enable: true }
}} primaryYAxis={{
labelFormat: 'n0',
lineStyle: { width: 0 }, rangePadding: 'None',
majorTickLines: { width: 0 }
}} title='Sales Analysis' bearFillColor='#2ecd71' bullFillColor='#e74c3d' height='350'>
<Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines,
EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator, Export,
AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator]} />
<StockChartSeriesCollectionDirective>
<StockChartSeriesDirective type='Candle' animation={{ enable: true }}>
</StockChartSeriesDirective>
</StockChartSeriesCollectionDirective>
</StockChartComponent>
</div>
</div>
);
}
;
export default App;
ReactDOM.render(<App />, document.getElementById("charts"));import * as React from "react";
import * as ReactDOM from "react-dom";
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import { useEffect, useRef, useState } from 'react';
import {
StockChartComponent, StockChartSeriesCollectionDirective, StockChartSeriesDirective, Inject, ITooltipRenderEventArgs, IStockChartEventArgs, ChartTheme,
DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines
} from '@syncfusion/ej2-react-charts';
import {
EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator,
AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator, Export
} from '@syncfusion/ej2-react-charts';
import { chartData } from './datasource';
function App() {
const [hasData, setHasData] = React.useState(false);
var chart: StockChartComponent | null;
React.useEffect(() => {
if (hasData) {
const buttonContainer = document.getElementById("syncfusionButtonContainer");
if (buttonContainer) {
ReactDOM.unmountComponentAtNode(buttonContainer);
}
}
}, [hasData]);
const SAMPLE_CSS = `
#noDataTemplateContainer {
height: inherit;
width: inherit;
}
.light-bg {
background-color: #fafafa;
color: #000000;
}
.template-align img {
max-width: 150px;
/* Adjust size as needed */
max-height: 150px;
margin-top: 55px;
}
.load-data-btn {
border-radius: 4px;
}
.template-align {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
flex-direction: column;
}
#syncfusionButtonContainer {
margin-top: 5px;
}`;
const noDataTemplate = `
<div id="noDataTemplateContainer" class="light-bg">
<div class="template-align">
<img src="no-data.png" alt="No Data"/>
</div>
<div class="template-align">
<p style="font-size: 15px; margin: 10px 0 10px;"><strong>No data available to display.</strong></p>
</div>
<div class="template-align">
<div id="syncfusionButtonContainer"></div>
</div>
</div>
`;
// Function to load data when button is clicked
const loadData = () => {
if (chart) {
(chart as StockChartComponent).series[0].dataSource = chartData;
}
};
// Function to load data when button is clicked
const loadedChartData = () => {
if (!hasData) {
const buttonContainer = document.getElementById("syncfusionButtonContainer");
if (buttonContainer && !buttonContainer.hasChildNodes()) {
// Create the button element using React.createElement
const buttonElement = React.createElement(ButtonComponent, {
id: "loadDataButton",
content: "Load Data",
iconCss: "e-icons e-refresh",
cssClass: "load-data-btn e-outline",
isPrimary: false,
onClick: loadData
});
ReactDOM.render(buttonElement, buttonContainer);
}
}
};
return (
<div>
{/* Custom No Data Template with Button */}
<style>{SAMPLE_CSS}</style>
{/* Chart Component */}
<div id="chart-container">
<StockChartComponent id='stockchart' ref={g => chart = g} loaded={loadedChartData} noDataTemplate={noDataTemplate}
primaryXAxis={{
valueType: 'DateTime',
majorGridLines: { width: 0 }, majorTickLines: { color: 'transparent' },
crosshairTooltip: { enable: true }
}}
primaryYAxis={{
labelFormat: 'n0',
lineStyle: { width: 0 }, rangePadding: 'None',
majorTickLines: { width: 0 }
}}
title='Sales Analysis'
bearFillColor='#2ecd71'
bullFillColor='#e74c3d'
height='350'
>
<Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, RangeAreaSeries, Trendlines,
EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, MomentumIndicator, SmaIndicator, AtrIndicator, Export,
AccumulationDistributionIndicator, MacdIndicator, StochasticIndicator]} />
<StockChartSeriesCollectionDirective>
<StockChartSeriesDirective type='Candle' animation={{ enable: true }}>
</StockChartSeriesDirective>
</StockChartSeriesCollectionDirective>
</StockChartComponent>
</div>
</div>
)
};
export default App;
ReactDOM.render(<App />, document.getElementById("charts"));Live Stock Chart
The Stock Chart can be updated in real time by pushing new and modified OHLC (open, high, low, close, volume) values into an existing candle series without re-rendering the entire chart. This is achieved with the help of the addPoint and setData methods exposed on a StockSeries instance.
-
setData(point, animationDuration)– replaces the current forming candle with the supplied point. Use this when you want to update the price of the candle that is currently being built. -
addPoint(point, animationDuration)– appends a brand-new candle to the end of the series. Use this when a new time bucket starts (for example, every new minute on a one-minute candle).
A typical real-time workflow uses both methods together:
- Start with a set of historical candles loaded through
dataSource. - On every tick, call
setDatato mutate the values of the in-progress candle. - When the candle interval elapses, call
addPointto begin a new candle whose open price matches the previous close.
In the following example, simulated one-minute OHLC data is generated locally and the chart is updated every 100 ms (using setInterval) to demonstrate live behavior. The forming candle is updated with setData, and a new candle is appended with addPoint every ten ticks.
import * as React from "react";
import * as ReactDOM from "react-dom";
import {
StockChartComponent, StockChartSeriesCollectionDirective, StockChartSeriesDirective, Inject,
DateTime, CandleSeries, LastValueLabel
} from '@syncfusion/ej2-react-charts';
const ONE_MINUTE_MS = 60 * 1000;
const UPDATE_INTERVAL_MS = 100;
const UPDATES_PER_CANDLE = 10;
const UPDATE_ANIMATION_DURATION = 0;
const ADD_ANIMATION_DURATION = 300;
const INITIAL_CANDLE_COUNT = 120;
const INITIAL_PRICE = 375;
let stockChart = null;
let stockData = [];
let updateTimer = null;
let updateIndex = 0;
function randomBetween(minimum, maximum) {
return minimum + Math.random() * (maximum - minimum);
}
function correctFloat(value) {
return Number(value.toFixed(2));
}
function getCurrentMinute() {
return Math.floor(Date.now() / ONE_MINUTE_MS) * ONE_MINUTE_MS;
}
function createHistoricalCandle(timestamp, openingPrice) {
const movement = randomBetween(-1.5, 1.5);
const close = correctFloat(Math.max(1, openingPrice + movement));
const high = correctFloat(
Math.max(openingPrice, close) + randomBetween(0.05, 0.7)
);
const low = correctFloat(
Math.max(1, Math.min(openingPrice, close) - randomBetween(0.05, 0.7))
);
return {
x: new Date(timestamp),
open: correctFloat(openingPrice),
high: high,
low: low,
close: close,
volume: Math.round(randomBetween(1000, 5000))
};
}
function createInitialLocalData() {
const currentMinute = getCurrentMinute();
const startingTime =
currentMinute - (INITIAL_CANDLE_COUNT - 1) * ONE_MINUTE_MS;
let price = INITIAL_PRICE;
stockData = [];
for (let index = 0; index < INITIAL_CANDLE_COUNT; index++) {
const timestamp = startingTime + index * ONE_MINUTE_MS;
const candle = createHistoricalCandle(timestamp, price);
stockData.push(candle);
price = candle.close;
}
}
function getCandleSeries() {
const chart = stockChart;
if (chart && chart.series && chart.series.length &&
typeof chart.series[0].setData === 'function' &&
typeof chart.series[0].addPoint === 'function') {
return chart.series[0];
}
return null;
}
function createUpdatedCandle(currentCandle) {
const movement = correctFloat(randomBetween(-1.5, 1.5));
const newClose = correctFloat(Math.max(1, currentCandle.close + movement));
return {
x: currentCandle.x,
open: currentCandle.open,
high: correctFloat(Math.max(currentCandle.high, newClose)),
low: correctFloat(Math.min(currentCandle.low, newClose)),
close: newClose,
volume: currentCandle.volume + Math.round(randomBetween(10, 100))
};
}
function createNewCandle(previousCandle) {
const openingPrice = previousCandle.close;
return {
x: new Date(previousCandle.x.getTime() + ONE_MINUTE_MS),
open: openingPrice,
high: openingPrice,
low: openingPrice,
close: openingPrice,
volume: Math.round(randomBetween(1000, 5000))
};
}
function updateCurrentPoint(candle) {
const series = getCandleSeries();
if (!series) { return; }
series.setData(candle, UPDATE_ANIMATION_DURATION);
}
function addNewPoint(candle) {
const series = getCandleSeries();
if (!series) { return; }
series.addPoint(candle, ADD_ANIMATION_DURATION);
}
function processDynamicUpdate() {
if (!stockData.length) { return; }
const lastIndex = stockData.length - 1;
const currentCandle = stockData[lastIndex];
const shouldAddNewCandle =
updateIndex > 0 && updateIndex % UPDATES_PER_CANDLE === 0;
if (shouldAddNewCandle) {
const newCandle = createNewCandle(currentCandle);
stockData.push(newCandle);
addNewPoint(newCandle);
} else {
const updatedCandle = createUpdatedCandle(currentCandle);
stockData[lastIndex] = updatedCandle;
updateCurrentPoint(updatedCandle);
}
updateIndex++;
}
function startDynamicUpdates() {
if (updateTimer !== null) { return; }
updateTimer = window.setInterval(processDynamicUpdate, UPDATE_INTERVAL_MS);
}
function stopDynamicUpdates() {
if (updateTimer !== null) {
window.clearInterval(updateTimer);
updateTimer = null;
}
}
function App() {
const loaded = (args) => {
stockChart = (args.chart && args.chart.ej2Instances)
? args.chart.ej2Instances[0]
: null;
startDynamicUpdates();
};
createInitialLocalData();
React.useEffect(() => {
const handleBeforeUnload = () => { stopDynamicUpdates(); };
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
stopDynamicUpdates();
};
}, []);
return (
<StockChartComponent id='stockcharts'
width='1100px'
height='455px'
title='Live Stock Data'
theme='Material'
chartArea={{ border: { width: 0 } }}
primaryXAxis={{ valueType: 'DateTime', labelFormat: 'HH:mm' }}
primaryYAxis={{ labelPosition: 'Outside' }}
seriesType={[]}
indicatorType={[]}
trendlineType={[]}
periods={[
{ text: '1H', interval: 1, intervalType: 'Hours', selected: true },
{ text: 'All' }
]}
enableCustomRange={false}
loaded={loaded}>
<StockChartSeriesCollectionDirective>
<StockChartSeriesDirective
dataSource={stockData}
type='Candle'
xName='x'
open='open'
high='high'
low='low'
close='close'
volume='volume'
lastValueLabel={{
enable: true,
background: '#e74c3d',
dashArray: '3,2',
lineWidth: 1,
font: { color: '#ffffff', size: '11px' }
}} />
</StockChartSeriesCollectionDirective>
<Inject services={[DateTime, CandleSeries, LastValueLabel]} />
</StockChartComponent>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('charts'));import * as React from "react";
import * as ReactDOM from "react-dom";
import {
StockChartComponent, StockChartSeriesCollectionDirective, StockChartSeriesDirective, Inject,
DateTime, CandleSeries, LastValueLabel, IStockChartEventArgs
} from '@syncfusion/ej2-react-charts';
interface StockData {
x: Date;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
const ONE_MINUTE_MS: number = 60 * 1000;
const UPDATE_INTERVAL_MS: number = 100;
const UPDATES_PER_CANDLE: number = 10;
const UPDATE_ANIMATION_DURATION: number = 0;
const ADD_ANIMATION_DURATION: number = 300;
const INITIAL_CANDLE_COUNT: number = 120;
const INITIAL_PRICE: number = 375;
let stockChart: StockChartComponent | null = null;
let stockData: StockData[] = [];
let updateTimer: number | null = null;
let updateIndex: number = 0;
function randomBetween(minimum: number, maximum: number): number {
return minimum + Math.random() * (maximum - minimum);
}
function correctFloat(value: number): number {
return Number(value.toFixed(2));
}
function getCurrentMinute(): number {
return Math.floor(Date.now() / ONE_MINUTE_MS) * ONE_MINUTE_MS;
}
function createHistoricalCandle(timestamp: number, openingPrice: number): StockData {
const movement: number = randomBetween(-1.5, 1.5);
const close: number = correctFloat(Math.max(1, openingPrice + movement));
const high: number = correctFloat(
Math.max(openingPrice, close) + randomBetween(0.05, 0.7)
);
const low: number = correctFloat(
Math.max(1, Math.min(openingPrice, close) - randomBetween(0.05, 0.7))
);
return {
x: new Date(timestamp),
open: correctFloat(openingPrice),
high: high,
low: low,
close: close,
volume: Math.round(randomBetween(1000, 5000))
};
}
function createInitialLocalData(): void {
const currentMinute: number = getCurrentMinute();
const startingTime: number =
currentMinute - (INITIAL_CANDLE_COUNT - 1) * ONE_MINUTE_MS;
let price: number = INITIAL_PRICE;
stockData = [];
for (let index: number = 0; index < INITIAL_CANDLE_COUNT; index++) {
const timestamp: number = startingTime + index * ONE_MINUTE_MS;
const candle: StockData = createHistoricalCandle(timestamp, price);
stockData.push(candle);
price = candle.close;
}
}
function getCandleSeries(): any {
const chart: any = stockChart as any;
if (chart && chart.series && chart.series.length &&
typeof chart.series[0].setData === 'function' &&
typeof chart.series[0].addPoint === 'function') {
return chart.series[0];
}
return null;
}
function createUpdatedCandle(currentCandle: StockData): StockData {
const movement: number = correctFloat(randomBetween(-1.5, 1.5));
const newClose: number = correctFloat(Math.max(1, currentCandle.close + movement));
return {
x: currentCandle.x,
open: currentCandle.open,
high: correctFloat(Math.max(currentCandle.high, newClose)),
low: correctFloat(Math.min(currentCandle.low, newClose)),
close: newClose,
volume: currentCandle.volume + Math.round(randomBetween(10, 100))
};
}
function createNewCandle(previousCandle: StockData): StockData {
const openingPrice: number = previousCandle.close;
return {
x: new Date(previousCandle.x.getTime() + ONE_MINUTE_MS),
open: openingPrice,
high: openingPrice,
low: openingPrice,
close: openingPrice,
volume: Math.round(randomBetween(1000, 5000))
};
}
function updateCurrentPoint(candle: StockData): void {
const series: any = getCandleSeries();
if (!series) { return; }
series.setData(candle, UPDATE_ANIMATION_DURATION);
}
function addNewPoint(candle: StockData): void {
const series: any = getCandleSeries();
if (!series) { return; }
series.addPoint(candle, ADD_ANIMATION_DURATION);
}
function processDynamicUpdate(): void {
if (!stockData.length) { return; }
const lastIndex: number = stockData.length - 1;
const currentCandle: StockData = stockData[lastIndex];
const shouldAddNewCandle: boolean =
updateIndex > 0 && updateIndex % UPDATES_PER_CANDLE === 0;
if (shouldAddNewCandle) {
const newCandle: StockData = createNewCandle(currentCandle);
stockData.push(newCandle);
addNewPoint(newCandle);
} else {
const updatedCandle: StockData = createUpdatedCandle(currentCandle);
stockData[lastIndex] = updatedCandle;
updateCurrentPoint(updatedCandle);
}
updateIndex++;
}
function startDynamicUpdates(): void {
if (updateTimer !== null) { return; }
updateTimer = window.setInterval(processDynamicUpdate, UPDATE_INTERVAL_MS);
}
function stopDynamicUpdates(): void {
if (updateTimer !== null) {
window.clearInterval(updateTimer);
updateTimer = null;
}
}
function App() {
const loaded = (args: IStockChartEventArgs): void => {
stockChart = (args.chart && (args.chart as any).ej2Instances)
? ((args.chart as any).ej2Instances[0] as StockChartComponent)
: null;
startDynamicUpdates();
};
createInitialLocalData();
React.useEffect(() => {
const handleBeforeUnload = (): void => { stopDynamicUpdates(); };
window.addEventListener('beforeunload', handleBeforeUnload);
return (): void => {
window.removeEventListener('beforeunload', handleBeforeUnload);
stopDynamicUpdates();
};
}, []);
return (
<StockChartComponent id='stockcharts'
width='1100px'
height='455px'
title='Live Stock Data'
theme='Material'
chartArea={{ border: { width: 0 } }}
primaryXAxis={{ valueType: 'DateTime', labelFormat: 'HH:mm' }}
primaryYAxis={{ labelPosition: 'Outside' }}
seriesType={[]}
indicatorType={[]}
trendlineType={[]}
periods={[
{ text: '1H', interval: 1, intervalType: 'Hours', selected: true },
{ text: 'All' }
]}
enableCustomRange={false}
loaded={loaded}>
<StockChartSeriesCollectionDirective>
<StockChartSeriesDirective
dataSource={stockData}
type='Candle'
xName='x'
open='open'
high='high'
low='low'
close='close'
volume='volume'
lastValueLabel={{
enable: true,
background: '#e74c3d',
dashArray: '3,2',
lineWidth: 1,
font: { color: '#ffffff', size: '11px' }
}} />
</StockChartSeriesCollectionDirective>
<Inject services={[DateTime, CandleSeries, LastValueLabel]} />
</StockChartComponent>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('charts'));