How can you automatically scroll to the top of the window in Next.js after updating the search value in a search bar?

Picture a scenario where there is a button placed somewhere. Once this button is clicked, the text on it moves to my search bar. How can I also make the window scroll down to the search bar after the value is set in the Input element displayed below?

          <Flex
            flexDirection="column"
            justifyContent="center"
            alignItems="center"
            maxWidth="90%"
            mt={4}
          >
            {!filteredBlogPosts.length && 'No posts found.'}
            {filteredBlogPosts.map((frontMatter) => (
              <>
              <BlogPost
                key={frontMatter.title + frontMatter.lastPublishedOn}
                 handleSearch={(anyKey) => setSearchValue(anyKey)}
                 // Your code goes here for scrolling after setting the key for the search 
                {...frontMatter}
              />
              </>
            ))}
          </Flex>

And, this is the <Input> field

            <Input
              aria-label="Search"
              borderColor="blue.500"
              onChange={(e) => setSearchValue(e.target.value)}
              placeholder="Search"
              value={searchValue}
              // Alternatively, should I implement scrolling here? How?
              autoFocus
              onFocus={e => e.currentTarget.select()}
            />

Is this task manageable? If so, kindly provide some code examples.

Much appreciated!

Answer №1

If anyone encounters this problem later on, I successfully resolved it by implementing the following straightforward function.

    const scrollToTop = myKey => {
    window.scrollTo(0, 0);
    frontMatter.handleSearch(myKey)
  };

Then, I included the scrollToTop function in the button's onClick event.

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

Error in GitHub Action: Uploading NPM Package

I encountered an issue with the "publish npm package github action" name: Publish package on NPM on: release: types: [created] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@ ...

Error encountered when Jest is testing the rendering of a landing page that contains a video component set to autoplay

I'm working on a landing page in React that features an autoplay video upon loading. However, I encountered an error while running tests: console.error Error: Not implemented: HTMLMediaElement.prototype.play This is the test code that caused the er ...

Using Material-UI version 1, pass the outer index to the MenuItem component when clicked

Within my component, there is a Table that displays rows generated from a custom array of objects. In the last TableCell, I aim to include an icon button that, upon being clicked, opens a Menu containing various MenuItem actions (such as edit and delete). ...

Having trouble submitting a form with React and Formik

Here is the Model (popup) code I am using to send the user's email address to the backend service. The Model component is being rendered in my Login Component. However, I am facing an issue where I am unable to submit this form. Despite having working ...

No elements can be located within the iframe as per Cypress's search

I've been attempting to access elements within an iframe using the guidance provided in this article here, but I'm facing an issue where Cypress is unable to locate anything within the iframe. Below is a snippet of my test code: describe('s ...

Creating a wider background color for active nav bar links in CSS - A step-by-step guide

I've been working on customizing a CSS navbar and I've managed to get it to work as desired. However, I'm facing an issue with the active state background color, which seems to be the same width as the text itself. I've spent hours sear ...

Next.js is optimized for simplicity and ease-of-use, making it

I'm currently experimenting with integrating the Express Router in Next.js by utilizing their example of a custom-express-server as my starting point. My approach involves external route definitions in routes/router.js, which looks like this: Here is ...

The issue arose with NextJs 13 and Framer Motion where the module 'v8' could not be resolved

I keep encountering this persistent error in my app directory while attempting to implement page transition animations with framer motion. Despite my efforts, I continue to come across the v8 error. Resources on resolving this issue are scarce - does anyon ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

Can anyone explain why I keep encountering an endless loop when using react hooks?

Having a bit of trouble with fetching data from a JS file that is mimicking an API with some endpoint methods. When I console log the data, everything seems fine, but for some reason, I keep running into an infinite loop when using hooks. I've tried t ...

Having difficulty entering text into the Material UI TextField

I am encountering an issue with a button that opens up a Material UI Dialog containing a TextField. However, I am unable to click into the TextField to input any text. Additionally, when clicking on the button to open the Dialog, I receive the error messag ...

Error: The function is not defined in React-Redux when attempting to use React Final Form

I am currently in the process of developing a store that manages login information. However, when I dispatch with the action, I encounter an error message in the console. Error TypeError: Object(...) is not a function at onSubmit (Login.js:66) at O ...

Tips for creating a multi-line cell in a React data grid

Having an issue with react-data-grid where it only displays single line text instead of multi line text. Any suggestions on how to fix this? Check out the sandbox example here: https://codesandbox.io/s/5vy2q8owj4?from-embed ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...

Adjust CardMedia Images to match their content in the new MUI 5 version

I’m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

website: What is the best way to embed an input field within an image?

Is it possible to incorporate an image into my website design similarly to Google's simple approach? <img src... done... > Additionally, I would like to add an input box over the text area of the picture. How can I achieve this? ...

Issues encountered with Nextjs 13.4 and Next-Auth 4.2 regarding the signIn("credentials", { }); functionality not functioning as expected

When using next-auth credentials in my current project, I encountered an issue with the signIn() function from next-auth/react. It appears that the redirection to the admin page persists regardless of whether the login details are correct or not. {error: n ...

Retrieving parameters from within iframe (child)

I currently have an embedded Iframe within a website, with both residing on different domains that I own. My goal is to pass a query parameter to the src attribute of the iframe. <iframe id="iframe" title="Survey" allowtr ...

Can API Routes be utilized to construct pages in Next.JS using getStaticProps/getStaticPaths?

I'm currently developing a static Next.JS application integrated with MongoDB. Is it advisable to utilize API routes for constructing pages within my static Next.JS app? For instance, implementing the GET method to retrieve products in getStaticProps ...

Socket.on seems to be malfunctioning

Currently, I am in the process of creating a message board for practice purposes and have successfully implemented notifications and a chat application using socket.io. My next goal is to add basic video call functionality, but I have encountered some dif ...