react-scroll-to-component icon indicating copy to clipboard operation
react-scroll-to-component copied to clipboard

Does not work in production mode when used on a Gatsby site

Open rennehir opened this issue 7 years ago • 7 comments

"dependencies": {
    "gatsby": "^2.0.0",
    "react-scroll-to-component-ssr": "^1.0.0",
    ...
}

Tried with the ssr version and the original one. Works with gatsby develop but not when built and served. Is there a plugin I need or have I missed something?

rennehir avatar Oct 15 '18 19:10 rennehir

Hi, same problem here: this is my error with gatsby build:

Module not found: Error: Can't resolve 'raf'

valse avatar Oct 29 '18 17:10 valse

Same here. Even after installing missing raf and tween as peer dependencies.

WhippetsAintDogs avatar Nov 20 '18 19:11 WhippetsAintDogs

Okay, I found a solution. It seems that a Gatsby site in production when you set a ref on a component, it stays null. But... if the ref is set on the most encapsulating element in the component's render method, it doesn't stay null.

The way to do it is to set the ref on the component and use a React.forwardRef in the component like this:

// Parent container:

this.servicesRef = React.createRef()

render() {
    return (
      <Layout>
        <Header servicesRef={this.servicesRef} /> // it won't be null if forwardRef is used in Services
        <Services
          ref={this.servicesRef}
        />
        …
      </Layout>
    )
  }

// Child component:

const Services = React.forwardRef((props, ref) => (
  <div ref={ref}>
   …
  </div>
))

WhippetsAintDogs avatar Nov 20 '18 20:11 WhippetsAintDogs

same issue here. Is anyone come up with a solution?

csabat avatar Dec 18 '18 00:12 csabat

Mine works, see my previous comments 😜

WhippetsAintDogs avatar Dec 18 '18 03:12 WhippetsAintDogs

I got it building and working in production using @WhippetsAintDogs's way. Install the two dependencies, have a look at the sample code above, and use it like this or similar:

<a onClick={() => scrollToComponent(this.servicesRef.current,{ offset: 0, align: 'middle', duration: 500, ease:'inCirc'})}>Get a project</a>

richjava avatar Feb 19 '19 21:02 richjava

I have also had fun with this issue. However I am using react hooks i.e.

const MyComponent() { 
   const ref = React.useRef<HTMLDivElement>(null)
   const appState = React.useContext(AppState)

   appState.updateRef('my-thing-to-see', ref)

   return (
       <div ref={ref}>Something to see</div>
   )
}

and the only thing I needed to do was npm install -s raf tween. I'm not sure if this is the correct way to use hooks or fix the issue but it certainly appears fixed from here

Meberem avatar Mar 13 '19 11:03 Meberem