1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【react】gsapのScrollTriggerのpinを使うと、別ページ移動時にエラーが出るの解決方法

Last updated at Posted at 2023-01-06

エラー内容

Unhandled Runtime Error
NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Before

  useEffect(() => {
    const pagesEl = pagesRef?.current
    if (!pagesEl) return
    const pagesWrapperEl = pagesWrapperRef?.current
    if (!pagesWrapperEl) return
    const verticalTextEl = verticalTextRef?.current
    if (!verticalTextEl) return

    const tl = gsap.timeline({
      scrollTrigger: {
        trigger: '#horizontal-scroll',
        start: 'top -40rem',
        end: () => `+=${pagesEl.clientWidth - pagesWrapperEl.clientWidth}`,
        scrub: 0.3,
        pin: true,
        anticipatePin: 1,
        invalidateOnRefresh: true,
      },
    })

    tl.to(pagesEl, {
      x: () => -(pagesEl.clientWidth - pagesWrapperEl.clientWidth),
    })
  }, [])

After

  useLayoutEffect(() => {
    const pagesEl = pagesRef?.current
    if (!pagesEl) return
    const pagesWrapperEl = pagesWrapperRef?.current
    if (!pagesWrapperEl) return
    const verticalTextEl = verticalTextRef?.current
    if (!verticalTextEl) return

    const tl = gsap.timeline({
      scrollTrigger: {
        trigger: '#horizontal-scroll',
        start: 'top -40rem',
        end: () => `+=${pagesEl.clientWidth - pagesWrapperEl.clientWidth}`,
        scrub: 0.3,
        pin: true,
        anticipatePin: 1,
        invalidateOnRefresh: true,
      },
    })

    tl.to(pagesEl, {
      x: () => -(pagesEl.clientWidth - pagesWrapperEl.clientWidth),
    })

    return () => {
      ScrollTrigger.killAll()
    }
  }, [])

載せるためにちょっとコードを省いたので、へんなところがあったらごめんなさい。
みそは、useLayoutEffectに変わってるところ。
その中の最後のクリーンアップ関数で、アンマウント時にScrollTriggerをkillしてます。
これで別ページ遷移時に消えるので、エラーがなくなります。

[参考]
https://greensock.com/forums/topic/28327-scrolltrigger-breaks-react-router/

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?