Step 1: 프로젝트 구조
pages
|-- index.js
components
|-- FadeInSection.js
styles
|-- globals.css
Step 2: CSS 애니메이션 정의 (styles/globals.css)
.fade-in-section {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}
.fade-in-section.is-visible {
opacity: 1;
transform: none;
}
Step 3: Intersection Observer를 사용하는 FadeInSection 컴포넌트 작성 (components/FadeInSection.js)
import React, { useRef, useEffect, useState } from 'react';
import '../styles/globals.css';
const FadeInSection = ({ children }) => {
const domRef = useRef();
const [isVisible, setVisible] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => setVisible(entry.isIntersecting));
});
const currentDomRef = domRef.current;
if (currentDomRef) {
observer.observe(currentDomRef);
}
return () => {
if (currentDomRef) {
observer.unobserve(currentDomRef);
}
};
}, []);
return (
<div
className={`fade-in-section ${isVisible ? 'is-visible' : ''}`}
ref={domRef}
>
{children}
</div>
);
};
export default FadeInSection;
Step 4: FadeInSection 컴포넌트를 사용하는 Index 페이지 작성 (pages/index.js)
import React from 'react';
import FadeInSection from '../components/FadeInSection';
export default function Home() {
return (
<div className="App">
<h1>Scroll down to see the effect</h1>
<FadeInSection>
<div style={{ height: '100vh', backgroundColor: 'lightcoral' }}>
<h2>Section 1</h2>
</div>
</FadeInSection>
<FadeInSection>
<div style={{ height: '100vh', backgroundColor: 'lightseagreen' }}>
<h2>Section 2</h2>
</div>
</FadeInSection>
<FadeInSection>
<div style={{ height: '100vh', backgroundColor: 'lightblue' }}>
<h2>Section 3</h2>
</div>
</FadeInSection>
</div>
);
}
Step 5: 글로벌 CSS 적용 (pages/_app.js)
Next.js에서 글로벌 CSS 파일을 적용하려면 _app.js 파일에서 import 해야 합니다.
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
728x90
'DEVELOPE > 리액트 NEXT JS' 카테고리의 다른 글
Next.js로 반응형 웹사이트 개발하기 (3) | 2024.12.03 |
---|---|
리액트 페이지네이션 코드 (0) | 2024.03.07 |