Search code examples
htmlcssreactjsrenderviewport

Rendering html on top without changing viewport in React?


I want to render a component <Top /> above another component <Bottom /> in React. The structure is like this:

...
[top, setTop] = useState(false);
[bottom, setBottom] = useState(true);
...

return (
<div>
 top && (<Top />)
 bottom && (<Bottom />)
 <button onClick = { () => setTop(true) } />
</div>
)

The problem is, when the user sees <Bottom /> and clicks the button which renders <Top />, the viewport changes because there is an "instant scrolling" to <Top />.

Is there a way to render a component but keep the viewport (what the user is currently seeing) still ?

Should I use CSS or javascript tricks ?


Solution

  • To maintain the scroll position, you can use useEffect hook with the reference to the element. Here's a hint:

    useEffect(() => {
      // keep scroll position of bottom elememnt
      let currentPosition = bottomElementRef.scrollTop // first run
      if (top) {
       // update scroll position when top element is appended
       bottomElementRef.scrollTop = currentPosition // second run when top
      }
    },[top])
    

    Hope, this helps you to solve the issue.