@duxapp/react-native-chartjs is a React Native wrapper for chart.js built on top of @duxapp/react-native-canvas.
If your project has not installed @shopify/react-native-skia yet, install it first:
yarn add @shopify/react-native-skiaor
npm install @shopify/react-native-skiaThen install @duxapp/react-native-chartjs:
yarn add @duxapp/react-native-chartjsor
npm install @duxapp/react-native-chartjsRequired peer dependencies:
reactreact-native@shopify/react-native-skia
import { useEffect, useState } from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { Chart } from '@duxapp/react-native-chartjs';
import {
ArcElement,
BarController,
BarElement,
BubbleController,
CategoryScale,
Chart as ChartJS,
DoughnutController,
Filler,
Legend,
LineController,
LineElement,
LinearScale,
PieController,
PointElement,
PolarAreaController,
RadarController,
RadialLinearScale,
ScatterController,
Tooltip,
} from 'chart.js';
let registered = false;
const ensureRegister = () => {
if (registered) {
return;
}
ChartJS.register(
ArcElement,
BarController,
BarElement,
BubbleController,
CategoryScale,
DoughnutController,
Filler,
Legend,
LineController,
LineElement,
LinearScale,
PieController,
PointElement,
PolarAreaController,
RadarController,
RadialLinearScale,
ScatterController,
Tooltip
);
registered = true;
};
const labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const createConfig = () => ({
type: 'bar',
data: {
labels,
datasets: [
{
label: 'Sales',
data: labels.map(() => Math.round(Math.random() * 300)),
backgroundColor: '#3b82f6',
},
],
},
options: {
animation: {
duration: 800,
easing: 'easeOutCubic' as const,
},
maintainAspectRatio: false,
plugins: {
legend: { display: false },
},
scales: {
y: { beginAtZero: true },
},
},
});
export default function Demo() {
ensureRegister();
const [config, setConfig] = useState(() => createConfig());
useEffect(() => {
const timer = setInterval(() => {
setConfig(createConfig());
}, 1200);
return () => clearInterval(timer);
}, []);
return (
<ScrollView contentContainerStyle={styles.content}>
<Chart config={config} style={styles.chart} />
</ScrollView>
);
}
const styles = StyleSheet.create({
content: {
padding: 20,
},
chart: {
width: '100%',
height: 320,
borderRadius: 18,
overflow: 'hidden',
},
});- Register the Chart.js controllers, elements, scales, and plugins you use before rendering charts.
configdrives chart updates. Keep it in state or otherwise replace it intentionally when data changes.picturedefaults totruebecause it usually gives better rendering performance with the canvas backend.- Touch input is forwarded to Chart.js through the underlying canvas hook so hover/click style interactions can still work.