Skip to content

Commit

Permalink
Fix site crashing with certain anchor links (#3107)
Browse files Browse the repository at this point in the history
* Add safeQuerySelector function
* Fix site crashing with certain anchor links
  • Loading branch information
julieg18 authored Dec 21, 2021
1 parent 5f52875 commit faeb64e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/components/Link/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useLocation } from '@reach/router'
import GatsbyLink from 'gatsby-link'
import { getRedirect } from '../../utils/shared/redirects'
import { scrollIntoLayout, getScrollNode } from '../../utils/front/scroll'
import safeQuerySelector from '../../utils/front/safeQuerySelector'

export type ILinkProps = {
children: React.ReactNode
Expand Down Expand Up @@ -78,7 +79,7 @@ const ResultLinkComponent: React.FC<ILinkProps> = ({

const scrollToHash = (hash: string, scrollOptions = {}): void => {
if (hash) {
scrollIntoLayout(document.querySelector(hash), {
scrollIntoLayout(safeQuerySelector(hash), {
waitImages: true,
...scrollOptions
})
Expand Down
3 changes: 2 additions & 1 deletion src/components/Page/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useLocation } from '@reach/router'

import { handleFrontRedirect } from '../../utils/shared/redirects'
import { scrollIntoLayout, getScrollNode } from '../../utils/front/scroll'
import safeQuerySelector from '../../utils/front/safeQuerySelector'

import * as styles from './styles.module.css'

Expand All @@ -11,7 +12,7 @@ export const useAnchorNavigation = (): void => {

useEffect(() => {
if (location.hash) {
const node = document.querySelector(location.hash)
const node = safeQuerySelector(location.hash)

if (node) {
scrollIntoLayout(node, { waitImages: true })
Expand Down
10 changes: 10 additions & 0 deletions src/utils/front/safeQuerySelector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const safeQuerySelector = (query: string): null | Element => {
try {
const el = document.querySelector(query)
return el
} catch (err) {
return null
}
}

export default safeQuerySelector

0 comments on commit faeb64e

Please sign in to comment.