How to display HTML on top without altering the viewport in React?

I am trying to display a component <Top /> above another component <Bottom /> in React. The code structure is as follows:

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

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

The issue I am facing is that when the user clicks the button to render <Top /> while seeing <Bottom />, there is an "instant scrolling" effect that changes the viewport position to <Top />.

Is there a way to render the component without changing the current viewport position?

Should I consider using CSS or javascript techniques to achieve this?

Answer №1

If you want to maintain the scroll position, consider using the useEffect hook along with a reference to the specific element. Below is an example:

useEffect(() => {
  // store the current scroll position of the bottom element
  let currentPosition = bottomElementRef.scrollTop // initial run
  if (top) {
    // update the scroll position when a top element is added
    bottomElementRef.scrollTop = currentPosition // second run for top
  }
},[top])

I hope this explanation assists you in resolving the problem.

Answer №2

Give this a shot:

try {
  return (
    <div>
      {header && <Header />}
      {footer && <Footer />}
      <button onClick={() => setHeader(true)} />
    </div>
  );
} catch (error) {
  console.log('An error occurred: ' + error);
}

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

Hover over CSS sprite

My anchor tag looks like this: <a href="#"> <i class="ico01"></i> <span>Text</span> </a> The ico01 class applies an image using CSS sprite. I want to change the background color of the entire content inside the a ...

Programmatically simulate a text cursor activation as if the user has physically clicked on the input

I have been attempting to input a value into a text field using JavaScript, similar to the Gmail email input tag. However, I encountered an issue with some fancy animations that are tied to certain events which I am unsure how to trigger, illustrated in th ...

Modifying the image height in a column using Bootstrap and JSON data

My webpage is dynamically generating images from a JSON file through a JavaScript file. However, the images are displaying at different heights, and I want each column to adjust to the height of the image to eliminate any gaps. Particularly, data with the ...

Positioning icon/image beside the input box

Currently, I have a form with two buttons in a row and an icon (paper clip) that I am attempting to align next to the buttons using UIKit. However, I am facing challenges in getting the alignment right without affecting the size of the elements. Below is a ...

Generating PDFs from websites using code

Currently, I have my resume available online as an HTML page at www.mysite.com/resume.html. Whenever I need a PDF version of it, I rely on Google Chrome's print dialog to save it as a PDF using my print CSS stylesheet. However, I am looking for a way ...

Having trouble understanding the odd behavior in IE7. Suddenly seeing a scrollbar appear when hovering

The webpage layout I am currently experiencing issues with can be found at the following link: When viewing this page in ie7 or ie8 Compatibility View mode, a strange horizontal scrollbar appears whenever I hover over one of the menu items. It seems that ...

Borders in my CSS/HTML table design

Hey, I'm currently facing an issue with my class project. I've created a table with a series of images to form a background image. However, there are borders on the table that I need to adjust. Here is the current look: I am trying to have a sq ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

What is it about the phone screen that makes media content so captivating?

My phone has a resolution of 2280x1080. I noticed that when using the following code, the background color changes to blue on my phone: @media (max-width: 500px) { body { background-color: blue; } } Interestingly, this feature stops working once "compute ...

Mastering CSS: Optimizing Div Placement Across Sections

I am currently working on developing a sleek and modern landing page with multiple sections, each designed to catch the eye. This style is all the rage at the moment, featuring large headers, ample padding, bold text, and a visually appealing divider betwe ...

Creating an Interactive Menu System with Nested Options in Angular 2

I have a JSON structure that I need to transform into a menu with sub-menus based on the value of the sub-menu_location field. Here's an example: { "data": [ { "menu_name": "Primary Operations", "enabled": true, "sub-menu_lo ...

Creating a button that seamlessly adapts to all browsers

I am encountering an issue with the positioning of a chat button on my website. Despite my efforts, the button does not remain in the desired location across different browsers and screen resolutions. The browser zoom also causes inconsistencies in the but ...

What is the reasoning behind setting the perspective to 1000 for carousel items in Bootstrap?

While working on customizing the bootstrap carousel, I came across this code snippet: .carousel-inner > .item { -webkit-transition: -webkit-transform .6s ease-in-out; -o-transition: -o-transform .6s ease-in-out; transit ...

Applying CSS transformations to scale up a div within its parent body

Having an issue with formatting an anchor link using transform scale attributes on hover. The link is inside a div that's aligned to the right, and I want it to enlarge when hovered over. However, this increase in size also affects the parent div, ca ...

What is the best way to add a textfield within an image?

Does anyone have a code snippet that can generate a "search box" like the one on www.dx.com? I was shocked to find that searching for "textfield inside image" only yielded results for "image inside textfield". ...

Switch Button Hyperlink in HTML/CSS

I have the following code: document.addEventListener("DOMContentLoaded", function(event) { (function() { requestAnimationFrame(function() { var banner; banner = document.querySelector('.exponea-banner3'); banner.classList ...

Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes t ...

Tips for Placing a Div in a Precise Location

I'm currently working with Bootstrap and I'm attempting to replicate a layout similar to the one used by Twitter, as shown in the screenshot below. The specific part I'm struggling with is where the profile picture is located. I want to add ...

Navigating to a particular div using a click event

I am trying to achieve a scrolling effect on my webpage by clicking a button that will target a specific div with the class "second". Currently, I have implemented this functionality using jQuery but I am curious about how to accomplish the same task using ...

Decrease the border-radius shorthand mixin, deactivate the variable

I have been working on creating a mixin for border-radius that will only apply when the values, determined by a variable, are greater than or equal to 0. I have set the default value in a variable as 3px, so if I input -1 or 'no', the border-radi ...