Хук useElementOnScreen, переключение стилей навбара

This commit is contained in:
Ifraim Solomonov committed 2024-03-01 20:58:48 +03:00
1 parent 0492530220
commit 8496cae1aa
4 files changed
+56 -4

No files matched your search

-1
View File
@@ -1,5 +1,4 @@
import { scb as logo } from '../../assets/images'; import { scb as logo } from '../../assets/images';
import { NavLink } from "react-router-dom";
import NavbarLink from './NavbarLink'; import NavbarLink from './NavbarLink';
import './Navbar.styles.scss'; import './Navbar.styles.scss';
+7 -2
View File
@@ -1,13 +1,13 @@
@import "../../assets/styles/theme.scss"; @import "../../assets/styles/theme.scss";
.navbar { .navbar {
position: absolute; position: fixed;
top: 0; top: 0;
width: 80%; width: 80%;
height: 60px; height: 60px;
max-height: 80px; max-height: 80px;
padding: 1em 10%; padding: 1em 10%;
background: transparent; background: $bg-secondary;
z-index: 1; z-index: 1;
display: flex; display: flex;
@@ -44,3 +44,8 @@
} }
} }
} }
.navbar.absolute {
position: absolute;
background: transparent;
}
+30
View File
@@ -0,0 +1,30 @@
import { useRef, useEffect, useState } from "react";
const useElementOnScreen = (options) => {
const containerRef = useRef(null);
const [isVisible, setIsVisible] = useState(false);
const observerCallback = (entries) => {
const [entry] = entries;
setIsVisible(entry.isIntersecting);
};
useEffect(() => {
const observer = new IntersectionObserver(observerCallback, options);
if (containerRef.current) {
observer.observe(containerRef.current);
}
return () => {
if (containerRef.current) {
observer.unobserve(containerRef.current);
}
}
}, [containerRef, options])
return [containerRef, isVisible];
}
export default useElementOnScreen;
+19 -1
View File
@@ -1,9 +1,27 @@
import { useEffect } from 'react';
import { News, Projects, Labs, Partners, Gallery, ContactUs } from './components'; import { News, Projects, Labs, Partners, Gallery, ContactUs } from './components';
import useElementOnScreen from '../../lib/useElementOnScreen';
function Main() { function Main() {
const [containerRef, isVisible] = useElementOnScreen({
root: null,
rootMargin: '0px',
threshold: 0,
});
useEffect(() => {
const [ navbar ] = document.getElementsByClassName('navbar');
if (isVisible) {
navbar.classList.add('absolute');
} else {
navbar.classList.remove('absolute');
}
}, [isVisible]);
return ( return (
<> <>
<header className="header"> <header className="header" id="mainpageheader" ref={containerRef}>
<h1>Думай иначе, будь креативным!</h1> <h1>Думай иначе, будь креативным!</h1>
<h2>Студенческое конструкторское бюро<br /> <h2>Студенческое конструкторское бюро<br />
"Компьютерное инновационное творчество"</h2> "Компьютерное инновационное творчество"</h2>