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

Support for multiple columns in React JSON Schema Form

Can multi column forms be generated using the React JSONSchema Form Library? I am currently utilizing Material UI for my project. ...

Unable to access the `isDragging` property in TypeScript when using the `useDrag` method from react-d

As a newcomer to utilizing react in combination with typescript, I am currently working on implementing a drag and drop feature using the react-dnd package along with typescript. I came across this helpful blog that has guided me through the process of dra ...

What is the best way to ensure that circles only touch each other by their edges?

Trying to align three circles touching each other has been a challenge for me. Although I have successfully managed to make two touch, the third one remains elusive. How can I ensure that all three circles are in contact with each other, especially when th ...

What is the functionality of background attachment fixed?

I am curious about how background images behave when the background-attachment property is set to fixed. Here are my questions: If I set a background image for a div with dimensions of 500px by 500px and add a 1px solid red border, then apply backgro ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Tips for speeding up page loading when using the same image multiple times on a page

Is it possible to utilize a JavaScript Image object? If yes, could you provide an illustrative example? And is it feasible to achieve this with jQuery? ...

When using React, I noticed that the AuthContext does not update when I change the state

After creating a useState ( [logined,setLogined] ) in authContext and sharing it as a value, I noticed that even when I change the logined value in signout, my Navbar does not re-render. This led me to place useEffect in Navbar to check the logined state ...

How can Prisma be used to create a model for a database table with a hyphen in its name?

One of the tables in my database has a hyphen in its name, for example, "user-cars". Unfortunately, I am unable to change the name to "user_cars". Is there any way for me to name the model as "user_cars" while still making it reference the "user-cars" ta ...

Exploring the Three JS Perspective Camera's Field of View and Distance Range

We have a model loaded on Three JS Fiber and notice that other projects with similar models have a more steady camera view, giving the illusion of the object being larger. However, our camera settings seem to be different: https://i.sstatic.net/xxYkB.png ...

What methods can be employed to reduce additional background tasks when altering a state in a React component?

Trying out Code I experimented with creating a React exercise code that showcases a bus and its seats. Reserved seats are marked in red and cannot be selected, while the remaining seats can be chosen by clicking on them and selecting a gender from a popup ...

What is the best way to transfer information from node.js to HTML?

This is a sample code in Node.js var http = require('http'); var request = require("request"); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!& ...

remove all content from tinymce editor in react

I'm currently utilizing the tinymce editor within my project. Here's the code snippet: <Editor initialValue={selectedDocument.html_content} init={{ pl ...

Creating UL tabs using just HTML and CSSHere's a step-by-step guide

Looking for help to accomplish this task. I already have the styling, but I want something to happen when I click on the tabs. Specifically, I want the div with the tab class names to show and hide upon clicking the tabs. Currently, nothing happens when I ...

Can BeautifulSoup be utilized to retrieve CSS from a webpage?

Currently, I am tackling a project that necessitates the full view of a webpage instead of just scattered lines entwined with images in HTML format. Is there a method to parse CSS alongside HTML using BeautifulSoup? Below is an excerpt from my code: from ...

I'm encountering an issue when trying to build a React application

Unable to perform EPERM operation, the command "mkdir c:" is not found when trying to create a React app using npx create-react-app myapp ...

Add a variety of input values to a div in designated spots

Objective: The aim is to allow the user to connect form fields with specific locations within a content from another div, and then add the text entered in individual input fields to those corresponding locations. Here is the link to the fiddle HTML: < ...

Refine your search by name following the implementation of a character-altering filter

Encountered a scenario in which there is a need to filter elements generated by the 'ng-repeat' directive. I have implemented a custom filter that replaces one character with another and vice versa for each element created. However, when attempt ...

Obtain the coordinates by clicking within the iframe and extending to the parent page

On my webpage, I have implemented an iframe that displays a small square containing information when clicked. However, I am facing an issue with the coordinates provided by the iframe via post message. The coordinates are accurate except when scrolling wit ...

Errors from jQuery validation are causing disruptions in my form's functionality

When jQuery validation error messages appear, they take up space and push other fields downwards. I want the error messages to adjust within the available space and not disrupt other fields or elements. Below is the jQuery validation code I'm currentl ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...