Table of Contents 개발 중 id와 hash(#)를 이용해서 목차 간 이동을 하려고 했는데,
블로그 컨텐츠가 shadow DOM으로 되어 있어서 작동하지 않았음.
// h2 컨텐츠에 id를 추가하는 함수
const getH2ElementsAndSetId = (shadow: ShadowRoot) => {
const temp: string[] = [];
const h2List = shadow.querySelectorAll('h2');
h2List.forEach((h2) => {
h2.id = formatUrl(h2.innerText);
temp.push(h2.innerText);
});
setIndexList(temp);
};
<li key={index}>
<Link
href={`#${indexUrl}`}
onClick={() => scrollToIndex(indexUrl)}
scroll={false}
>
{index}
</Link>
</li>
useEffect
와 scrollToIndex
함수를 만들어서 해결했다.. 근데 뭔가 마음에 안 들어... 근데 다른 방법은 떠오르지가 않아요.....
// PostIndexList
const scrollToIndex = (id: string) => {
document
.querySelector('#content')
?.shadowRoot?.getElementById(id)
?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
if (indexList) scrollToIndex(decodeURI(location.hash.slice(1)));
}, [indexList]);