0

I'm currently working on a pie chart for which I want to change the layout depending on the size of the window (namely change the position of the legend from left to bottom).

function PieChart() {
    const { width } = useWindowSize();

    return (
        <React.Fragment>
            <Pie
                data={data}
                width={width < size.smallDevices ? 100 : "auto"}
                legend={width < size.smallDevices ? legendOptsSmall : legendOptsLarge}
            />
            <div>{width < size.smallDevices ? "Small devices" : "Big devices"}</div>
        </React.Fragment>
    );
}

In this example, where width returns the width of the window, the div correctly changes from "Small devices" to "Big devices" while I resize the window, but the Pie from react-chartjs-2 doesn't change. However, when refreshed, the Pie correctly loads with the right layout (for small devices or big devices, depending on the situation). Only the hot refresh is failing.

Any idea on how to get a hot refresh?

Thanks!

Thanh-Quy Nguyen
  • 2,995
  • 7
  • 30
  • 46
  • you should set width in your state then add an `addEventListener` for `resize` and update your state, your component should then re-render – Nico Sep 17 '19 at 10:25
  • Unless I didn't understand your answer, it is already the case. useWindowSize is a custom hook using an "addEvenListener", that's why the div detecting "Small devices" or "Big devices" re-renders correctly. – Thanh-Quy Nguyen Sep 17 '19 at 12:54

1 Answers1

0

I agree with Cozzani You should set width/height in your state then add width/height on addEventListener() for resizing and mean while you should update your state then component will re-render, when component re-render your width/height will be updated. You can have a look on example gist

SHUVO MUSA
  • 544
  • 6
  • 9
  • As I said to Cozzani, unless I didn't understand your answer, it is already the case. useWindowSize is a custom hook using an "addEvenListener", that's why the div detecting "Small devices" or "Big devices" re-renders correctly. – Thanh-Quy Nguyen Sep 17 '19 at 12:55
  • Also, I suspect your example to work because you are not changing anything else than the width, which is already handled by the package. In my case, I'm trying to change the position of the legend, but a display true/false would also work to check if an example is working. – Thanh-Quy Nguyen Sep 17 '19 at 13:27