Skip to content

Commit a7d70b7

Browse files
author
Endo
committed
fixed useOffset hook to add multiple listeners using addEventListener, not replacement
1 parent 9e71a68 commit a7d70b7

3 files changed

Lines changed: 21 additions & 18 deletions

File tree

src/components/Header.tsx

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,16 @@ import MenuIcon from "@mui/icons-material/Menu";
1010
import Avatar from "@mui/material/Avatar";
1111
import Tooltip from "@mui/material/Tooltip";
1212
import MenuItem from "@mui/material/MenuItem";
13-
import SearchBox from "./SearchBox";
1413
import useOffSetTop from "src/hooks/useOffSetTop";
14+
import { APP_BAR_HEIGHT } from "src/constant";
1515
import Logo from "./Logo";
16+
import SearchBox from "./SearchBox";
1617
import NetflixNavigationLink from "./NetflixNavigationLink";
1718

1819
const pages = ["My List", "Movies", "Tv Shows"];
1920

2021
const Header = () => {
21-
const isOffset = useOffSetTop(100);
22+
const isOffset = useOffSetTop(APP_BAR_HEIGHT);
2223

2324
const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(
2425
null
@@ -45,15 +46,15 @@ const Header = () => {
4546
return (
4647
<AppBar
4748
sx={{
48-
height: 70,
49-
boxShadow: 0,
5049
px: "60px",
51-
bgcolor: "transparent",
50+
height: APP_BAR_HEIGHT,
5251
backgroundImage: "none",
53-
...(isOffset && {
54-
bgcolor: "primary.main",
55-
boxShadow: (theme) => theme.shadows[4],
56-
}),
52+
...(isOffset
53+
? {
54+
bgcolor: "primary.main",
55+
boxShadow: (theme) => theme.shadows[4],
56+
}
57+
: { boxShadow: 0, bgcolor: "transparent" }),
5758
}}
5859
>
5960
<Toolbar disableGutters>

src/constant/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ export const COMMON_TITLES: CustomGenre[] = [
1212
];
1313

1414
export const YOUTUBE_URL = "https://www.youtube.com/watch?v=";
15+
export const APP_BAR_HEIGHT = 70;

src/hooks/useOffSetTop.tsx

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
1-
import { useState, useEffect } from "react";
1+
import { useState, useEffect, useCallback } from "react";
22

33
export default function useOffSetTop(top: number) {
44
const [offsetTop, setOffSetTop] = useState(false);
5+
const onScroll = useCallback(() => {
6+
if (window.pageYOffset > top) {
7+
setOffSetTop(true);
8+
} else {
9+
setOffSetTop(false);
10+
}
11+
}, [top]);
512

613
useEffect(() => {
7-
window.onscroll = () => {
8-
if (window.pageYOffset > top) {
9-
setOffSetTop(true);
10-
} else {
11-
setOffSetTop(false);
12-
}
13-
};
14+
window.addEventListener("scroll", onScroll);
1415
return () => {
15-
window.onscroll = null;
16+
window.removeEventListener("scroll", onScroll);
1617
};
1718
}, [top]);
1819

0 commit comments

Comments
 (0)