Refactor refBreak (#76)

This commit is contained in:
Szymon Szlachtowicz 2021-10-15 14:48:59 +02:00 committed by GitHub
parent 7ec7344b74
commit 345e5772e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 10 deletions

View File

@ -1,6 +1,6 @@
import React, { createContext, useContext } from "react";
import { useRefWidthBreak } from "../hooks/useRefWidthBreak";
import { useRefBreak } from "../hooks/useRefBreak";
const NarrowContext = createContext<boolean>(false);
@ -14,6 +14,6 @@ interface NarrowProviderProps {
}
export function NarrowProvider({ children, myRef }: NarrowProviderProps) {
const narrow = useRefWidthBreak(myRef, 736);
const narrow = useRefBreak(myRef?.current?.offsetWidth ?? 0, 736);
return <NarrowContext.Provider value={narrow} children={children} />;
}

View File

@ -1,15 +1,11 @@
import React, { useEffect, useState } from "react";
import { useEffect, useState } from "react";
export function useRefWidthBreak(
myRef: React.RefObject<HTMLHeadingElement>,
sizeThreshold: number
) {
export function useRefBreak(dimension: number, sizeThreshold: number) {
const [widthBreak, setWidthBreak] = useState(false);
useEffect(() => {
const checkDimensions = () => {
const width = myRef?.current?.offsetWidth ?? 0;
if (width && width < sizeThreshold && width > 0) {
if (dimension && dimension < sizeThreshold && dimension > 0) {
if (widthBreak === false) {
setWidthBreak(true);
}
@ -24,7 +20,7 @@ export function useRefWidthBreak(
return () => {
window.removeEventListener("resize", checkDimensions);
};
}, [myRef, widthBreak, myRef?.current?.offsetWidth]);
}, [dimension, widthBreak]);
return widthBreak;
}