Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bd9aa2c

Browse files
committed
Move hooks to its own file
1 parent e85d299 commit bd9aa2c

File tree

2 files changed

+38
-35
lines changed

2 files changed

+38
-35
lines changed

www/src/hooks/use-active-hash.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { useEffect, useState } from "react"
2+
3+
export const useActiveHash = itemIds => {
4+
const [activeHash, setActiveHash] = useState(``)
5+
6+
useEffect(() => {
7+
const observer = new IntersectionObserver(
8+
entries => {
9+
entries.forEach(entry => {
10+
if (entry.isIntersecting) {
11+
setActiveHash(entry.target.id)
12+
}
13+
})
14+
},
15+
{ rootMargin: `0% 0% -100% 0%` }
16+
)
17+
18+
itemIds.forEach(id => {
19+
observer.observe(document.querySelector(`#${id}`))
20+
})
21+
22+
return () => {
23+
itemIds.forEach(id => {
24+
observer.unobserve(document.querySelector(`#${id}`))
25+
})
26+
}
27+
}, [])
28+
29+
useEffect(() => {
30+
if (activeHash) {
31+
window.history.replaceState(null, null, `#${activeHash}`)
32+
}
33+
}, [activeHash])
34+
35+
return activeHash
36+
}

www/src/templates/template-docs-markdown.js

Lines changed: 2 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/** @jsx jsx */
22
import { jsx } from "theme-ui"
3-
import React, { useEffect, useState } from "react"
3+
import React from "react"
44
import { Helmet } from "react-helmet"
55
import { graphql } from "gatsby"
66
import { MDXRenderer } from "gatsby-plugin-mdx"
@@ -16,40 +16,7 @@ import Breadcrumb from "../components/docs-breadcrumb"
1616
import Container from "../components/container"
1717
import PrevAndNext from "../components/prev-and-next"
1818

19-
const useActiveHash = itemIds => {
20-
const [activeHash, setActiveHash] = useState(``)
21-
22-
useEffect(() => {
23-
const observer = new IntersectionObserver(
24-
entries => {
25-
entries.forEach(entry => {
26-
if (entry.isIntersecting) {
27-
setActiveHash(entry.target.id)
28-
}
29-
})
30-
},
31-
{ rootMargin: `0% 0% -100% 0%` }
32-
)
33-
34-
itemIds.forEach(id => {
35-
observer.observe(document.querySelector(`#${id}`))
36-
})
37-
38-
return () => {
39-
itemIds.forEach(id => {
40-
observer.unobserve(document.querySelector(`#${id}`))
41-
})
42-
}
43-
}, [])
44-
45-
useEffect(() => {
46-
if (activeHash) {
47-
window.history.replaceState(null, null, `#${activeHash}`)
48-
}
49-
}, [activeHash])
50-
51-
return activeHash
52-
}
19+
import { useActiveHash } from "../hooks/use-active-hash"
5320

5421
const getHeadingIds = (toc, traverseFullDepth = false) => {
5522
if (!toc) return []

0 commit comments

Comments
 (0)