Skip to content

Commit

Permalink
fix: moved smooth-scroll application to useEffect (#2868)
Browse files Browse the repository at this point in the history
  • Loading branch information
werdnanoslen authored Apr 11, 2024
1 parent b9fb0d9 commit bc87158
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
@media not (prefers-reduced-motion) {
html {
.smooth-scroll {
scroll-behavior: smooth;
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/components/InPageNavigation/InPageNavigation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { userEvent } from '@testing-library/user-event'
import { InPageNavigation } from './InPageNavigation'
import { HeadingLevel } from '../../types/headingLevel'
import { CONTENT } from './content'
import styles from './InPageNavigation.module.scss'

describe('InPageNavigation component', () => {
const props = {
Expand Down Expand Up @@ -50,6 +51,7 @@ describe('InPageNavigation component', () => {
name: 'On this page',
})
expect(heading).toBeInTheDocument()
expect(document.querySelector('html')).toHaveClass(styles['smooth-scroll'])
})

it('sets the heading and title', () => {
Expand Down
8 changes: 6 additions & 2 deletions src/components/InPageNavigation/InPageNavigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const InPageNavigation = ({
...divProps
}: InPageNavigationProps &
Omit<JSX.IntrinsicElements['div'], 'content'>): React.ReactElement => {
const classes = classnames('usa-in-page-nav', styles.target, className)
const asideClasses = classnames('usa-in-page-nav', styles.target, className)
const { className: navClassName, ...remainingNavProps } = navProps || {}
const navClasses = classnames('usa-in-page-nav__nav', navClassName)
const { className: mainClassName, ...remainingMainProps } = mainProps || {}
Expand Down Expand Up @@ -57,12 +57,16 @@ export const InPageNavigation = ({
const observer = new IntersectionObserver(handleIntersection, observerOptions)
useEffect(() => {
document.querySelectorAll('h2,h3').forEach((h) => observer.observe(h))
document.querySelector('html')?.classList.add(styles['smooth-scroll'])
return () => {
document.querySelector('html')?.classList.remove(styles['smooth-scroll'])
}
})

return (
<div className="usa-in-page-nav-container" {...divProps}>
<aside
className={classes}
className={asideClasses}
aria-label={title}
data-testid="InPageNavigation">
<nav className={navClasses} {...remainingNavProps}>
Expand Down

0 comments on commit bc87158

Please sign in to comment.