andrehigher
andrehigher

Reputation: 30

Is there a way to scroll up a stateless component?

I have two divs on the page side by side and the left one is a stateless component showing the information regarding the option selected from the right side.

The page itself has overflow: hidden and the left side component has overflow-y: scroll allowing the user to scroll down and up.

Until here everything is good however when the user scrolls down and then select another piece in the right side, I should scroll this stateless component up.

return (
    <div
      style='display: flex; flex: 1 1 0; height: 100%; overflow-y: scroll'
      ref={myElement => {
        this.myElement = myElement
      }}
    >
       My content
    </div>
  )

And once we have a ref on this element, I could have something like this:

this.myElement.scrollTop = 0

I am trying to put a ref in this div to be able to scroll once this component receives any update as https://stackoverflow.com/a/33204783/1696029 but the ref does not work with stateless component.

Any ideas how can I scroll up only this left stateless component?

Upvotes: 0

Views: 511

Answers (1)

Ankur Mittal
Ankur Mittal

Reputation: 65

Consider the following component heirarchy

<Parent>
  <LeftComponent />
  <RightComponent />
</Parent>

You can define a ref function for LeftComponent on Parent.. Something like

leftComponentRefFunction(myElement) {
  this.myElement = myElement
}

Dont forget to bind this function inside parent constructor.

And after this, send leftComponentRefFunction function as prop to the stateless component

<LeftComponent refFunction={this.leftComponentRefFunction} />

Now inside the LeftComponent use the prop function to set the ref

return (
<div
  style='display: flex; flex: 1 1 0; height: 100%; overflow-y: scroll'
  ref={props.refFunction}
>
   My content
</div>

)

What we're basically doing here is lifting the state logic up to the parent component.

Now you'll have access to the leftComponent ref on the parent this. and hence you will be able to set the scroll to 0

Upvotes: 1

Related Questions