In this article, we learn how to use amCharts in React app.
First open React app and install the amCharts5 dependency.
npm install @amcharts/amcharts5
Now we create a line chart using amCharts. So, import amCharts as a module.
import * as am5 from "@amcharts/amcharts5"; import am5themes_Animated from "@amcharts/amcharts5/themes/Animated"; import * as am5xy from "@amcharts/amcharts5/xy";
Create a central object whose name is the root and set a theme in that.
Here we create a line chart so we have to put here a new Root “chartdiv”.
let root = am5.Root.new("chartdiv"); root.setThemes([am5themes_Animated.new(root)]);
Then set the data and Axis which we want to show. After that create a series of column shows. Like,
let xAxis = chart.xAxes.push( am5xy.CategoryAxis.new(root, { renderer: am5xy.AxisRendererX.new(root, {}), categoryField: "category" }) ); xAxis.data.setAll(data); let series1 = chart.series.push( am5xy.ColumnSeries.new(root, { name: "Series", xAxis: xAxis, yAxis: yAxis, valueYField: "value1", categoryXField: "category" }) ); series1.data.setAll(data);
And only we have to return only which have an id which value is created new root value.
<div id="chartdiv" style={{ width: "30%", height: "500px" }}></div>
So, App.js looks like this,
import * as am5 from "@amcharts/amcharts5"; import am5themes_Animated from "@amcharts/amcharts5/themes/Animated"; import * as am5xy from "@amcharts/amcharts5/xy"; import { useEffect } from 'react'; function App() { useEffect(() => { let root = am5.Root.new("chartdiv"); root.setThemes([am5themes_Animated.new(root)]); let chart = root.container.children.push( am5xy.XYChart.new(root, { panY: false, layout: root.verticalLayout }) ); // Define data let data = [ { category: "Research", value1: 1000, value2: 588 }, { category: "Marketing", value1: 1200, value2: 1800 }, { category: "Sales", value1: 850, value2: 1230 } ]; // Create Y-axis let yAxis = chart.yAxes.push( am5xy.ValueAxis.new(root, { renderer: am5xy.AxisRendererY.new(root, {}) }) ); // Create X-Axis let xAxis = chart.xAxes.push( am5xy.CategoryAxis.new(root, { renderer: am5xy.AxisRendererX.new(root, {}), categoryField: "category" }) ); xAxis.data.setAll(data); // Create series let series1 = chart.series.push( am5xy.ColumnSeries.new(root, { name: "Series", xAxis: xAxis, yAxis: yAxis, valueYField: "value1", categoryXField: "category" }) ); series1.data.setAll(data); let series2 = chart.series.push( am5xy.ColumnSeries.new(root, { name: "Series", xAxis: xAxis, yAxis: yAxis, valueYField: "value2", categoryXField: "category" }) ); series2.data.setAll(data); }, []) return ( <div id="chartdiv" style={{ width: "30%", height: "500px" }}></div> ); } export default App;
Output:-