React scroll position shifting when state is modified

Attempting to incorporate a basic show more button with react using the useState hook. Everything is functioning properly except for the fact that when the content is toggled, the vertical scroll position abruptly shifts down by the size of the div that was displayed. Essentially, the displayed content is positioned above the "Show More" button instead of expanding the text and maintaining the scroll position at the start of the text. Despite extensive searching, I have been unable to find a graceful solution that does not involve remembering and restoring scroll positions. Below is a code snippet that illustrates my issue.

import {useState} from "react"

export default function Test() {
    let text = (
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquet porttitor vulputate. Morbi pellentesque blandit est vel
            dictum. Fusce mattis dolor in diam tempor commodo. Integer eu consequat magna. Cras placerat magna vitae nunc auctor, quis
            sodales ex hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis dapibus condimentum elementum.
            Phasellus ultrices quis quam vel dignissim. Suspendisse ac sapien iaculis, suscipit nunc vel, commodo lorem. Vestibulum a arcu
            ut mi commodo ullamcorper. Vestibulum massa nunc, sodales a diam et, condimentum finibus quam. Nulla aliquet lacus id rhoncus
            maximus. Phasellus sed vehicula erat, eget suscipit ipsum. Donec nulla arcu, luctus nec mattis eu, cursus sit amet libero.
            Nullam at egestas orci. Sed tempus convallis enim vitae rutrum. Sed mattis vel dolor eu laoreet. Nam a aliquet massa, eu
            vulputate lacus. Fusce condimentum, eros in scelerisque dictum, turpis nisl sagittis diam, auctor blandit massa nunc eget purus.
            Praesent vitae ultrices risus. Vivamus sed leo ipsum. Maecenas rhoncus, urna sit amet interdum maximus, risus odio ullamcorper
            aug
        </p>
    )

    const [show, setShow] = useState(false)

    return (
        <>
            <div style={{height: 1000, backgroundColor: "red"}}></div>
            <button onClick={() => setShow(!show)}>THIS IS HOW I WANT IT TO WORK</button>
            <div style={{width: "20%"}}>{show ? text : "Not showing anything"}</div>
            <button onClick={() => setShow(!show)}>BUT ON THIS BUTTON THAT IS BELOW TEXT</button>
            <div style={{height: 1000, backgroundColor: "blue"}}></div>
        </>
    )
}

Runnable code snippet:

function Test() {
    let text = (
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquet porttitor vulputate. Morbi pellentesque blandit est vel
            dictum. Fusce mattis dolor in diam tempor commodo. Integer eu consequat magna. Cras placerat magna vitae nunc auctor, quis
            sodales ex hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis dapibus condimentum elementum.
            Phasellus ultrices quis quam vel dignissim. Suspendisse ac sapien iaculis, suscipit nunc vel, commodo lorem. Vestibulum a arcu
            ut mi commodo ullamcorper. Vestibulum massa nunc, sodales a diam et, condimentum finibus quam. Nulla aliquet lacus id rhoncus
            maximus. Phasellus sed vehicula erat, eget suscipit ipsum. Donec nulla arcu, luctus nec mattis eu, cursus sit amet libero.
            Nullam at egestas orci. Sed tempus convallis enim vitae rutrum. Sed mattis vel dolor eu laoreet. Nam a aliquet massa, eu
            vulputate lacus. Fusce condimentum, eros in scelerisque dictum, turpis nisl sagittis diam, auctor blandit massa nunc eget purus.
            Praesent vitae ultrices risus. Vivamus sed leo ipsum. Maecenas rhoncus, urna sit amet interdum maximus, risus odio ullamcorper
            aug
        </p>
    )

    const [show, setShow] = React.useState(false)

    return (
        <div>
            <div style={{height: 1000, backgroundColor: "red"}}></div>
            <button onClick={() => setShow(!show)}>THIS IS HOW I WANT IT TO WORK</button>
            <div style={{width: "20%"}}>{show ? text : "Not showing anything"}</div>
            <button onClick={() => setShow(!show)}>BUT ON THIS BUTTON THAT IS BELOW TEXT</button>
            <div style={{height: 1000, backgroundColor: "blue"}}></div>
        </div>
    )
}

ReactDOM.render(<Test/>, document.getElementById("test"));
<body>
  <div id="test"></div>

  <!-- React.js CDN links -->
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

  <!-- Babel (essential for JSX syntax - https://babeljs.io/docs/en/#jsx-and-react) -->
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

</body>

Answer №1

Success! After some investigation, I discovered that in Chrome, the CSS property overflow-anchor defaults to auto, causing the clicked button to act as a scroll anchor when new content is loaded. To resolve this issue, you can either globally set overflow-anchor: none; or apply it directly to the button.

function Test() {
    let text = (
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquet porttitor vulputate. Morbi pellentesque blandit est vel
            dictum. Fusce mattis dolor in diam tempor commodo. Integer eu consequat magna. Cras placerat magna vitae nunc auctor, quis
            sodales ex hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis dapibus condimentum elementum.
            Phasellus ultrices quis quam vel dignissim. Suspendisse ac sapien iaculis, suscipit nunc vel, commodo lorem. Vestibulum a arcu
            ut mi commodo ullamcorper. Vestibulum massa nunc, sodales a diam et, condimentum finibus quam. Nulla aliquet lacus id rhoncus
            maximus. Phasellus sed vehicula erat, eget suscipit ipsum. Donec nulla arcu, luctus nec mat
        
<body>
  <div id="test"></div>

  <!-- React.js CDN links -->
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

  <!-- Babel (essential for JSX syntax - https://babeljs.io/docs/en/#jsx-and-react) -->
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the ins and outs of utilizing the latest @Shopify/app-bridge in tandem with @Shopify/polaris-react

Shopify has recently launched their brand new @shopify/app-bridge, but it seems like there is some confusion on how to integrate it with @shopify/polaris. An attempt was made to create a React component that utilizes both app-bridge and polaris to show a ...

Click anywhere outside the sidemenu to close it

I want the menu to behave like the side menu on Medium. When the side menu is open and the user clicks outside of #sidebar-wrapper, the side menu should close. Currently, I have to click the toggle X to close the menu. html <a id="menu-toggle" href="# ...

Conceal the generic type property when exporting

In my components setup, a Wrapper manipulates its children (referred to as Components) by injecting a prop into each child using cloneElement. The challenge is that the props of the Component are generic. I don't want one of the props to be included i ...

Having trouble with the flexbox flex-direction: column property not functioning properly with the textarea element in Firefox?

Inconsistencies between Chrome and Firefox have been noticed in the following example. While the footer height is set to height:40px and appears fine in Chrome, it seems smaller in Firefox, around 35px. Any specific reasons for this difference? Link to t ...

Having trouble uploading a pdf file into a .tsx file

As a beginner in learning TypeScript, I recently embarked on building a portfolio website using React JS and TypeScript. However, I encountered a problem when trying to import a PDF file from my images into the resume.tsx file within my project folder. htt ...

What are some creative ways to customize v-slot:cell templates?

Currently, I have the following code snippet within a table: <template v-slot:cell(checkbox)="row" style="border-left='5px dotted blue'"> <input type="checkbox" v-model="row.rowSelected" @input="toggleS ...

Utilizing the ternary operator in React with JSS and Material-UI for efficient conditional rendering

I am trying to apply a specific CSS style based on certain conditions in my code. For simplicity, let's consider the following example. const num = 3 const useStyles = makeStyles({ root: { color: [num <= 5 ? "red" :"blue" ...

Struggling with CSS drop-down navigation bars

Lately, I've been dedicating my time to creating a small CSS menu, but it's just not cooperating the way I want it to. Despite playing around with different menus and adjusting positions and fonts, I can't seem to get it right. Initially, m ...

Ensure that the fixed header's width matches the size of the container div

The header element is contained within a div. I have positioned the header as fixed, leading to 2 issues: The width of the header extends beyond the width of the div container. It should align with the div. When the header is fixed, the other elements li ...

Animation of CSS with an image depicting a leaf swaying gently in the breeze

This project was a personal challenge for me, and I am quite satisfied with the approach I have developed. However, I am open to exploring alternative methods if there are any. The website I am working on features a logo that includes an image of a leaf. ...

Display the div in all browsers except for Internet Explorer

There's a message in a div that needs to be displayed on the webpage, but it's not showing up on Internet Explorer. Even after attempting the usual , as well as other recommendations, the message still remains hidden. What could I be overlooking ...

Adjust both scrollLeft and scrollTop at the same time

Is there a way to adjust both scrollLeft and scrollTop of a div at the same time? It seems to work in Chrome, Safari, and Opera when set sequentially, but Firefox (older than 4) and IE (even in IE9!) experience glitches where the page moves left and then d ...

Is it possible for an ul to be displayed beneath a white section within an li

I am working on a JQuery carousel that is displaying correctly, but I want to make a small adjustment to the content: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal" style="float: left; list-style: none ...

Enhance your Docker workflow with Visual Studio Code's advanced syntax highlighting for React

My React, TypeScript, and Docker project is up and running smoothly. However, my Visual Studio Code keeps showing errors such as missing types. Any suggestions on how to resolve this issue? https://i.sstatic.net/qSpeg.png https://i.sstatic.net/4R5AS.png ...

Tips for separating these two words onto two separate lines

I created this box using Angular Material, but I am having trouble breaking the words "1349" and "New Feedback" into two lines. Here's an image included in my design. Any tips on accomplishing this in Angular Material? Thank you! <style> . ...

React Navigation ran into an issue with the specified location

It seems that I am encountering an issue where it is displaying a message stating "no routes matched for location '/'". However, the Header file clearly shows that there is a home component defined for this URL. https://i.sstatic.net/26516LfM.jpg ...

Redux causing React component to load twice

I am encountering an issue with my Redux store where my component is loading twice whenever I access my redux action. Upon manual route loading, it initially returns two objects - one with an empty state and the other with an updated state. However, when s ...

Is it possible to create a touch menu on an iPhone by utilizing basic markup and implementing the :hover-state feature?

After finally launching my WordPress blog, I spent a significant amount of time developing the theme. When I attempted to view the site on my iPhone for the first time, I was surprised by what I saw. Initially, I thought creating a touch menu would be as s ...

display a div based on the user's choice

I am working with the following http://jsbin.com/useqa4/10 My query revolves around hovering over li elements in the submenu using the code snippet below: $(".submenuList li").hover(function () { $(".submenuCurrent").removeClass("submenuCurrent"); $( ...

"Why does my HTML5 video flash with a white screen right before it starts

I have been working on incorporating an OGG/MP4/OGV video file into my website by using HTML5 Video tags. However, I am encountering an issue where a white box flashes momentarily before the video loads. I attempted to change the background color of the vi ...