-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
35 lines (29 loc) · 907 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { useEffect, useState } from 'react';
const updateClassLists = (list, method) => {
list.forEach(({ selector, className }) => {
const element = document.querySelector(selector)?.classList;
if (!element) return;
if (method === 'add') {
element.add(className);
}
if (method === 'remove') {
element.remove(className);
}
});
};
export default function (selector, effectDependencies = [], additionalClassList = []) {
const [tocData, setTocData] = useState([]);
useEffect(() => {
const templateContext = [...document.querySelectorAll(selector)].map(({ innerText, id }) => ({
text: innerText,
id
}));
setTocData(templateContext);
updateClassLists(additionalClassList, 'add');
return () => {
setTocData('');
updateClassLists(additionalClassList, 'remove');
};
}, [...effectDependencies]);
return tocData;
}