C3.js is a high-level API on top of D3.js. It has an active community for support, is highly customizable, and benefits from having great code reusability. It has a steep learning curve and is more limited when it comes to the number of charts offered.
React is a popular JavaScript library for building user interfaces, particularly single-page applications where dynamic content needs to be updated without reloading the page. Developed by Facebook (now Meta Platforms), React has grown in popularity due to its simplicity, efficiency, and scalability. It allows developers to build large web applications that can change data without reloading the page, offering a responsive and fluid user experience. React has a virtual DOM for faster manipulation, a component based architecture, and a great community for support. It is efficient, flexible, and widely used in the market.
Integrating C3.js, a D3-based reusable chart library, with React allows for creating interactive and dynamic charts within React apps. This example demonstrates how to create a simple line chart in a React component using C3.js.
First, ensure both C3.js and D3.js are installed in your project, as C3.js is a D3-based library.
npm install c3 d3
Create a new React component where the chart will be rendered. This component will import C3.js and use it to generate a chart within a specified DOM element.
import React, { useEffect, useRef } from 'react';
import c3 from 'c3';
import 'c3/c3.css';
function LineChart() {
// Ref to attach the chart
const chartRef = useRef(null);
useEffect(() => {
// Generate the chart
const chart = c3.generate({
bindto: chartRef.current,
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
type: 'line' // Change type to 'bar', 'spline', etc. as needed
}
});
// Optional: Cleanup on component unmount
return () => {
chart.destroy();
};
}, []); // Empty dependency array means this effect runs once on mount
return (
<div>
<h2>Simple Line Chart</h2>
{/* Chart container */}
<div ref={chartRef}></div>
</div>
);
}
export default LineChart;
Once your component is ready, it can be rendered inside any part of your React application. For example, you can include it in your App.js file like so:
import React from 'react';
import LineChart from './LineChart'; // Adjust the import path as necessary
function App() {
return (
<div className="App">
<h1>My React App</h1>
<LineChart />
</div>
);
}
export default App;
This will render the line chart within your React application. You can customize the chart data, type, and other options as per your needs by modifying the c3.generate
configuration within the LineChart
component.