Framework/React

[React] recharts chart ๋„“์ด 100% ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ• (+ typescript)

yuri lee 2023. 4. 29. 17:32
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ €๋Š” recharts chart  ์ฐจํŠธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฐจํŠธ์˜ ๋„“์ด๋ฅผ ํ™”๋ฉด 100%์— ๋งž์ถฐ์„œ ๋ฟŒ๋ ค์ฃผ๊ณ  ์‹ถ์—ˆ๋Š”๋ฐ์š”. width ๊ฐ’์„ 100%๋กœ ์„ค์ •ํ•˜์ž ๋‹ค์Œ์˜ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. 

 

TS2322: Type 'string' is not assignable to type 'number'. 

 

import {NextPage} from "next";
import React from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';


const data = [
    {
        name: 'Jan',
        uv: 4000,
        pv: 2400,
        amt: 2400,
    },
    {
        name: 'Feb',
        uv: 3000,
        pv: 1398,
        amt: 2210,
    },
    {
        name: 'Mar',
        uv: 2000,
        pv: 9800,
        amt: 2290,
    },
  	...
    {
        name: 'Jul',
        uv: 3490,
        pv: 4300,
        amt: 2100,
    },
];
const MainChart: NextPage = () => {
    return (
        <div style={{ width: "100%" }}>
            <LineChart
                width={"100%"}
                height={300}
                data={data}
                margin={{
                    top: 5,
                    right: 30,
                    left: 20,
                    bottom: 5,
                }}
            >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{ r: 8 }} />
                <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
            </LineChart>
        </div>

    );
};

 

Why?

LineChart์˜ width ์†์„ฑ์—๋Š” px, em ๋“ฑ ๋‹จ์œ„๋ฅผ ํ•จ๊ป˜ ์จ์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋•Œ๋ฌธ์—  width={"100%"} ์ฒ˜๋Ÿผ ์ˆซ์ž ๋Œ€์‹  % ๊ฐ’์„ ํ• ๋‹นํ•  ๊ฒฝ์šฐ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

 

๊ทธ๋ž˜์„œ ๋‘๋ฒˆ์งธ ๋ฐฉ๋ฒ•์œผ๋กœ ์•„๋ž˜ stytle ์†์„ฑ์„ ์‚ฌ์šฉํ•ด๋ดค๋Š”๋ฐ์š”, ์•„์˜ˆ ํ‘œ ์ž์ฒด๊ฐ€ ํ™”๋ฉด์— ๊ทธ๋ ค์ง€์ง€ ์•Š๋”๋ผ๊ณ ์š” ;-;

style={{ width: "100%" }}

 

How to solve the problem

๊ตฌ๊ธ€๋ง์„ ํ†ตํ•ด ์•„๋ž˜์˜ ๋ฐฉ๋ฒ•์„ ์ฐพ์•˜์Šต๋‹ˆ๋‹ค. ResponsiveContainer ๋ฅผ ์ด์šฉํ•˜์—ฌ width๋ฅผ 100%๋กœ ์„ค์ •ํ•˜๋‹ˆ ์ฐจํŠธ๊ฐ€ ์˜ˆ์˜๊ฒŒ ๊ทธ๋ ค์กŒ์Šต๋‹ˆ๋‹ค :) ๐Ÿคฉ

<ResponsiveContainer width='100%' aspect={4.0/3.0}>
...
</ResponsiveContainer>

 

 

๋ฐ˜์‘ํ˜•