App.js
import React, { useRef, useState, useEffect } from "react";
import styled from "styled-components";
const DETAIL_NAV = [
{ idx: 0, name: "Section 1" },
{ idx: 1, name: "Section 2" },
{ idx: 2, name: "Section 3" },
{ idx: 3, name: "Section 4" },
// Add more sections as needed
];
const App = () => {
const scrollRef = useRef([]);
const navRef = useRef([]);
const [activeSection, setActiveSection] = useState(null);
const handleNavClick = (index) => {
setActiveSection(index);
};
useEffect(() => {
scrollRef.current[activeSection]?.scrollIntoView({ behavior: "smooth" });
setActiveSection(null);
}, [activeSection]);
useEffect(() => {
const changeNavBtnStyle = () => {
scrollRef.current.forEach((ref, idx) => {
if (ref.offsetTop - 180 < window.scrollY) {
navRef.current.forEach((ref) => {
ref.classList.remove("active");
});
navRef.current[idx].classList.add("active");
}
});
};
window.addEventListener("scroll", changeNavBtnStyle);
return () => {
window.removeEventListener("scroll", changeNavBtnStyle);
};
}, []);
return (
<div>
<Nav>
{DETAIL_NAV.map(({ idx, name }) => (
<NavBtn
key={idx}
ref={(ref) => (navRef.current[idx] = ref)}
onClick={() => handleNavClick(idx)}
className={activeSection === idx ? "active" : ""}
>
{name}
</NavBtn>
))}
</Nav>
<Section ref={(ref) => (scrollRef.current[0] = ref)}>
<h2>Section 1</h2>
<p>Content for section 1...</p>
</Section>
<Section ref={(ref) => (scrollRef.current[1] = ref)}>
<h2>Section 2</h2>
<p>Content for section 2...</p>
</Section>
<Section ref={(ref) => (scrollRef.current[2] = ref)}>
<h2>Section 3</h2>
<p>Content for section 3...</p>
</Section>
<Section ref={(ref) => (scrollRef.current[3] = ref)}>
<h2>Section 4</h2>
<p>Content for section 4...</p>
</Section>
{/* Add more sections as needed */}
</div>
);
};
const Nav = styled.nav`
position: sticky;
top: 0;
left: 0;
width: 100%;
background-color: #f0f0f0;
padding: 10px;
display: flex;
justify-content: center;
z-index: 999;
`;
const NavBtn = styled.button`
border: none;
background-color: transparent;
padding: 5px 10px;
margin: 0 5px;
font-weight: bold;
color: #555;
cursor: pointer;
outline: none;
&.active {
color: blue;
}
`;
const Section = styled.section`
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: #fafafa;
scroll-margin-top: 100px;
h2 {
font-size: 24px;
margin-bottom: 10px;
}
`;
export default App;
아주 좋은 학습용 코드를 구했다. 이번 주는 이 코드를 이해하고 투두리스트를 적용하는 것을 목표로 하겠다.