AdSense

網頁

2024/3/21

React 安裝Recharts圖表函式庫

React安裝圖表函式庫Recharts


安裝環境:

  • Node.js v16.20.2
  • npm 8.19.4
  • react ^18.2.0


事前要求

參考「React 使用Create React App建立React應用程式」建立React應用程式。


安裝

在React專案根目錄輸入npm install recharts開始安裝Recharts。

% npm install recharts

added 33 packages, changed 1 package, and audited 1998 packages in 6s

147 packages are looking for funding
  run `npm fund` for details

130 vulnerabilities (2 low, 84 moderate, 31 high, 13 critical)

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details

安裝後在專案的package.json可看到"recharts": "^2.12.3",


使用

在React專案根目錄/app下新增Chart.js內容如下。

Chart.js

import * as React from 'react';
import { LineChart, Line, XAxis, YAxis } from 'recharts';

const data = [
    {name: 'Page A', uv: 250, pv: 1000},
    {name: 'Page B', uv: 500, pv: 500},
    {name: 'Page C', uv: 250, pv: 1000},
];

export const Chart = () => {
    return (
        <LineChart width={600} height={200} data={data}>
            <Line type="monotone" dataKey="uv" stroke="#0099dd" />
            <Line type="monotone" dataKey="pv" stroke="#dd9900" />
            <XAxis dataKey="name" />
            <YAxis />
        </LineChart>
    )
}

修改App.js如下。

App.js

import './App.css';

import * as React from 'react';
import { Chart } from 'Chart';


function App() {
  return (
    <Chart/>
  )
}

export default App;

github


測試

啟動React專案,首頁顯示圖表效果如下。




沒有留言:

AdSense