Skip to content

Instantly share code, notes, and snippets.

@iammdmusa
Last active November 21, 2020 12:41
Show Gist options
  • Save iammdmusa/c5448ae6894bde7023cef7293d32e873 to your computer and use it in GitHub Desktop.
Save iammdmusa/c5448ae6894bde7023cef7293d32e873 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
export default function useWindowSize() {
const isClient = typeof window === 'object';
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined
};
}
const [windowSize, setWindowSize] = useState(getSize);
useEffect(() => {
if (!isClient) {
return false;
}
function handleResize() {
setWindowSize(getSize());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
}
import React from "react";
import ReactDOM from "react-dom";
import { Pie } from 'react-chartjs-2'
import useWindowSize from "./get-window-side-hot-refresh";
function PieChart() {
const size = useWindowSize();
return (
<React.Fragment>
<div>
Current width = {size.width}px
<br />
Current Height = {size.height}px
</div>
<Pie
data={data}
width={size.width}
/>
</React.Fragment>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<PieChart />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment