Handle Browser Window Resize in React

BackEnd_Ash.log·2020년 7월 17일
0

react

목록 보기
23/41

i use the rechart of react .
it very often happens , it is not responsive library.
it just adjusts width and height

when you want responsive width and height , you have to adjusts mounted to the DOM

how can i solve this ??

um... first very easy solution
anoter one use .
but , in practice this solution is rarely posssible .

so..

import React, { Component } from 'react';
import LineChart from 'chart-graphs';

export default class Chart extends Component {

  constructor() {
    super();
    this.state = {
      width:  800,
      height: 182
    }
  }

  /**
   * Calculate & Update state of new dimensions
   */
  updateDimensions() {
    if(window.innerWidth < 500) {
      this.setState({ width: 450, height: 102 });
    } else {
      let update_width  = window.innerWidth-100;
      let update_height = Math.round(update_width/4.4);
      this.setState({ width: update_width, height: update_height });
    }
  }

  /**
   * Add event listener
   */
  componentDidMount() {
    this.updateDimensions();
    window.addEventListener("resize", this.updateDimensions.bind(this));
  }

  /**
   * Remove event listener
   */
  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions.bind(this));
  }

  render() {
    return(
      <div id="lineChart"> 
         <LineChart width={this.state.width} height={this.state.height} /> 
      </div>
    );
  }
}

if you use react hooks

import React, { useState, useEffect } from "react";
import "./SvgChart.scss";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from "recharts";

const SvgChart = (data) => {
  const [widthState, setWidthState] = useState(800);
  const [heightState, setHeightState] = useState(350);
  const [marginState, setMarginState] = useState({});

  const updateDimesions = () => {
    if (window.innerWidth < 2000 && window.innerWidth > 1550) {
      setWidthState(750);
      setHeightState(350);
    } else {
      let update_width = window.innerWidth - 1200;
      let update_height = Math.round(update_width / 3.4);
      setWidthState(update_width);
      setHeightState(update_height);
    }
  };

  useEffect(() => {
    updateDimesions();
    window.addEventListener("resize", updateDimesions);
  });

  return (
    <div className="border">
      <LineChart
        width={widthState}
        height={heightState}
        data={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="value" stroke="orange" />
      </LineChart>
    </div>
  );
};
export default SvgChart;
profile
꾸준함이란 ... ?

0개의 댓글