简体   繁体   中英

Scroll to y location within react element with useRef

I have an component on my page that scrolls, but the rest doesn't. I want to scroll to a certain Y location within this element, when I change a useState value using a different component.

const scrollMe = useRef();  

useEffect(
        () => {
                if (scrollMe === true) {
                    scrollPanel.scrollTo(0, 300)
                }

        },
        [ scrollMe ]
    );

The scrollable component is like so:

 <div ref={scrollMe} onScroll={(e) => handleScroll(e)}>A mapped array</div>

The scroll function is as follows:

const handleScroll = (e) => {
    if (e.target.scrollTop !== 0) {
        setTopBarPosition(true);
    } else {
        setTopBarPosition(false);
    }
};

Setting the topBarPosition affects

<div className={`topBar ${topBarPosition === true ? 'topBarToTop' : ''}`}>
                    <TopBar/>
</div>

And the css class topBarToTop moves the topBar to the top of the page:

.topBarToTop {
    top: 30px;
}

How come I just get scrollMe.scrollTo is not a function ?

I made a codesandbox that illustrates what I'm trying to do:

https://codesandbox.io/s/react-hooks-counter-demo-izho9

You need to make some small changes, Please follow the code comments :

  useEffect(() => {
    // swap the conditions to check for childRef first
    if (childRef && topPosition) {

      // use to get the size (width, height) of an element and its position
      // (x, y, top, left, right, bottom) relative to the viewport.
      const { y } = childRef.current.getBoundingClientRect()

      // You have to call `current` from the Ref
      // Add the `scrollTo()` second parameter (which is left)
      childRef.current.scrollTo(y, 0)

      // Initially it was set to `false` and we change it to `true` when click on scroll
      // button then we change it back to `false` when re-render 
      setTopPosition(false)

    }
  }, [topPosition, childRef])

More about getBoundingClientRect()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM