Skip to content

Instantly share code, notes, and snippets.

@sp0033212000
Created November 3, 2020 09:48
Show Gist options
  • Save sp0033212000/b017819e724f988e1370def225bf1b42 to your computer and use it in GitHub Desktop.
Save sp0033212000/b017819e724f988e1370def225bf1b42 to your computer and use it in GitHub Desktop.
import React, {
useState,
useEffect,
useCallback,
useMemo,
ReactElement,
} from "react";
import { isScreenLessThanWidth } from "../../../../tools/format.checker";
type CardProps = {
isClick: boolean;
mainEl: (node: any) => void;
setIsClick: () => void;
};
type OwnProps = {
render: (props: CardProps) => ReactElement;
};
type Props = OwnProps;
const Card: React.FC<Props> = ({ render }) => {
const [isDevice, setIsDevice] = useState<boolean>(
isScreenLessThanWidth(1301)
);
const [isClick, setIsClick] = useState<boolean>(false);
const [containerNode, setContainerNode] = useState<HTMLLIElement | null>(
null
);
const [mainNode, setMainNode] = useState<HTMLElement | null>(null);
const containerEl = useCallback((node) => {
if (node) setContainerNode(node);
}, []);
const mainEl = useCallback((node) => {
if (node) setMainNode(node);
}, []);
useEffect(() => {
window.addEventListener("resize", () =>
setIsDevice(isScreenLessThanWidth(1301))
);
window.addEventListener("orientationchange", () =>
setIsDevice(isScreenLessThanWidth(1301))
);
return () => {
window.removeEventListener("resize", () =>
setIsDevice(isScreenLessThanWidth(1301))
);
window.removeEventListener("orientationchange", () =>
setIsDevice(isScreenLessThanWidth(1301))
);
};
}, []);
const onMainClick = () => {
if (isDevice) {
setIsClick((prev) => !prev);
}
};
const height = useMemo(
() => [
mainNode ? mainNode.offsetHeight - 1 : 0,
containerNode ? containerNode.scrollHeight : 0,
],
[containerNode, mainNode]
);
return (
<li
style={{
height: isDevice ? height[isClick ? 1 : 0] : "auto",
}}
ref={containerEl}
className={`plan__item card`}
>
{render({ isClick, mainEl, setIsClick: onMainClick })}
</li>
);
};
export default Card;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment