Intro
์๋ ํ์ธ์. ์ด๋ฒ ์๊ฐ์๋ React scroll ์คํฌ๋กค์ ์ปจํธ๋กคํ๋ ๋ฐฉ๋ฒ์ ๋ํด ์์๋ณด๊ฒ ์ต๋๋ค.
My case
์ ์ ๊ฒฝ์ฐ ์ปดํฌ๋ํธ ํ๋ฉด์ด ๋ค์๊ณผ ๊ฐ์ด ๊ตฌ์ฑ๋์ด ์์์ต๋๋ค. ๊ฒ์๊ธ ๋ฆฌ์คํธ๊ฐ ์๊ณ , ํน์ ๊ฒ์๊ธ์ ํด๋ฆญํ๋ ์๊ฐ ํน์ ๊ฒ์๊ธ์ ๋ํ ๋ด์ฉ์ด ๋ณด์ด๊ณ , ์๋๋ก ๋ค๋ฅธ ๊ฒ์๊ธ๋ก ์ด๋ํ ์ ์๋ ์ต์ ๊ฒ์๊ธ ๋ชฉ๋ก์ด ์์ต๋๋ค. ์ต์ ๊ฒ์๊ธ ๋ชฉ๋ก ์ค ํ๋๋ฅผ ํด๋ฆญํ๋ฉด, ๋ณธ๋ฌธ ๋ด์ฉ์ด ๋ณํ๋ ํ์์ ๋๋ค.
How to solve the problem
1. ๋์ div์ ref๋ฅผ ํ์ฉํ๊ธฐ ์ํด ์๋์ ์ฝ๋๋ฅผ ์ถ๊ฐํฉ๋๋ค.
const postDetailRef = useRef<HTMLDivElement>(null);
2. ์ ์ํ ref ๊ฐ์ div tag์ ํ ๋นํด์ค๋๋ค.
<div ref={postDetailRef}>
{postDetail && (
<section>
<h2>{postDetail.title}</h2>
<div>{postDetail.content}</div>
</section>
)}
{recentpost && recentpost.length > 0 && (
<section >
<h2>{postDetail?.categoryName}more post</h2>
<div >
{recentpost?.map((item: postRes, index: number) => {
return (
<button
type="button"
onClick={() => {
props.eventpostDetail(true, item.postId);
}}
>
<p>{item.title}</p>
</button>
);
})}
</div>
</section>
)}
</div>
3. ์์ธ ํ์ด์ง๋ฅผ ๊ฐ์ ธ์ค๋ API๋ฅผ ํธ์ถํ๋ ํจ์์ scrollTop ๊ฐ์ 0์ผ๋ก ํ ๋นํด์ค๋๋ค .
const getpostDetail = async (postId: number) => {
const { data } = await postAPI.getpostDetail(postId);
if (data.status === "200") {
setpostDetail(data.data);
if (postDetailRef?.current?.scrollTop) {
postDetailRef.current.scrollTop = 0;
}
}
};
์๋๋ ์ ์ฒด ์ฝ๋์ ๋๋ค. ์ฐธ๊ณ ํด์ฃผ์ธ์ :)
const postDetail: NextPage<Props> = (props) => {
const [postDetail, setpostDetail] = useState<postDetailRes>();
const [recentpost, setRecentpost] = useState<postRes[]>();
const postDetailRef = useRef<HTMLDivElement>(null);
useEffect(() => {
getpostDetail(props.id);
getRecentpostDetail(props.id);
}, [props.id]);
const getpostDetail = async (postId: number) => {
const { data } = await postAPI.getpostDetail(postId);
if (data.status === "200") {
setpostDetail(data.data);
if (postDetailRef?.current?.scrollTop) {
postDetailRef.current.scrollTop = 0;
}
}
};
const getRecentpostDetail = async (postId: number) => {
const { data } = await postAPI.getRecentpostDetail(postId);
if (data.status === "200") {
setRecentpost(data.data);
}
};
return (
<div ref={postDetailRef}>
{postDetail && (
<section>
<h2>{postDetail.title}</h2>
<div>{postDetail.content}</div>
</section>
)}
{recentpost && recentpost.length > 0 && (
<section >
<h2>{postDetail?.categoryName}more post</h2>
<div >
{recentpost?.map((item: postRes, index: number) => {
return (
<button
type="button"
onClick={() => {
props.eventpostDetail(true, item.postId);
}}
>
<p>{item.title}</p>
</button>
);
})}
</div>
</section>
)}
</div>
);
};
export default postDetail;