Adding a Pie Chart
Step 1: Basic Configuration
Create a new component named PieChart.js:
touch src/components/PieChart.js
Edit the file and set up the pie chart:
import React from "react";
import HighchartsReact from "highcharts-react-official";
import Highcharts from "highcharts";
const PieChart = () => {
const options = {
chart: {
type: "pie"
},
title: {
text: "Browser Market Share"
},
series: [
{
name: "Share",
data: [
{ name: "Chrome", y: 63.59 },
{ name: "Safari", y: 19.2 },
{ name: "Firefox", y: 4.2 },
{ name: "Edge", y: 3.4 },
{ name: "Other", y: 9.61 }
]
}
]
};
return <HighchartsReact highcharts={Highcharts} options={options} />;
};
export default PieChart;
Step 2: Rendering the Component
Update App.js to include the PieChart component:
import React from "react";
import PieChart from "./components/PieChart";
function App() {
return (
<div>
<h1>Highcharts in React</h1>
<PieChart />
</div>
);
}
export default App;
Run the application:
npm start
You should see an interactive pie chart displaying browser market shares.
Adding a Bar Chart
Step 1: Basic Configuration
Create another component named BarChart.js:
touch src/components/BarChart.js
Edit the file and set up the bar chart:
import React from "react";
import HighchartsReact from "highcharts-react-official";
import Highcharts from "highcharts";
const BarChart = () => {
const options = {
chart: {
type: "bar"
},
title: {
text: "Monthly Sales Data"
},
xAxis: {
categories: ["January", "February", "March", "April", "May"]
},
yAxis: {
title: {
text: "Sales (in USD)"
}
},
series: [
{
name: "Sales",
data: [5000, 7000, 8000, 6000, 9000]
}
]
};
return <HighchartsReact highcharts={Highcharts} options={options} />;
};
export default BarChart;
Step 2: Rendering the Component
Update App.js to include the BarChart component:
import React from "react";
import PieChart from "./components/PieChart";
import BarChart from "./components/BarChart";
function App() {
return (
<div>
<h1>Highcharts in React</h1>
<PieChart />
<BarChart />
</div>
);
}
export default App;
Styling and Customization
Highcharts is highly customizable. You can:
Change Colors: Modify the colors array in the options object.
Add Tooltips: Customize tooltips with the tooltip property.
Customize Legends: Adjust legends using the legend property.
For example, adding a custom tooltip in the bar chart:
tooltip: {
formatter: function () {
return `<b>${this.x}</b>: $${this.y}`;
}
}