Sustained concentration on NextJS

As I embark on my journey of building my very first NextJS site, I have encountered a strange anomaly.

Within my site's header, I have incorporated several <Link /> components that serve as links to different pages of my site. These links are adorned with simple focus styles created using the :focus selector in CSS.

Upon clicking on one of the links, the focus styles are correctly applied and the site smoothly transitions to the new URL. However, I have noticed that the focus styles persist even after the new page has finished loading.

Is there a method to eliminate the focus state during the transition to a new page?

I am hopeful that a knowledgeable individual can assist this fledgling NextJS developer. Thank you.

Answer №1

I was able to resolve the issue and wanted to share the solution for anyone facing a similar problem in the future.

The problem was that my header links were located in my custom _app.js file, which wasn't getting re-rendered and hence the focus state was persisting. To fix this, I moved my site boilerplate code out of _app.js and created a separate component for it, which then wraps around each page.

For example:

pages/_app.js

const App = ({ Component, pageProps }) => <Component {...pageProps} />;

export default App;

components/SiteLayout.js

import Head from "next/head";

const SiteLayout = ({ children }) => {
  return (
    <>
      <Head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <meta name="mobile-web-app-capable" content="yes" />
      </Head>
      <header>
        <Link href="my-page">
          <a>My page</a>
        </Link>
      </header>
      <main role="main">
        {children}
      </main>
    </>
  );
};

export default SiteLayout;

pages/my-page.js

import SiteLayout from "components/SiteLayout";

const MyPage = () => (
  <SiteLayout>
    <h1>My Page</h1>
  </SiteLayout>
);

export default MyPage;

Answer №2

One way to make this function is by adding an invisible input element to the code. By setting the height and width of the input to 0, the element remains hidden from view. Then, when the URL changes, focus can be directed to this input element.

import { withRouter } from 'next/router';
import React, { createRef, Component } from 'react';

class MyComponent extends Component {

    componentDidUpdate(prevProps) {
        if (this.props.router != prevProps.router) {
            this.input_ref.focus();
        }
    }

    input_ref = createRef()

    render() {
        return (
            <>
                {/* ... */}

                <input ref={this.input_ref} style={{width: 0, height: 0}} />

                {/* ... */}
            </>
        )
    }
}

export default withRouter(MyComponent);

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

I'm noticing that the top border for my span is smaller than the bottom one. What could

I am struggling to create an arrangement of three triangles in a line, with the first and third pointing up and the middle one pointing down. The upper triangle seems to be too small - any ideas on how to adjust this? Is there another way to achieve this ...

What steps should be taken to make mocha utilize the HTTP response?

Every time I make an http call, the function it returns causes my comparison to fail because [Function] is never equal to the value I want. Is there a way to make my assert statement consider the true/false flag within it? # test/helloWorld.js const othe ...

Utilizing Three.js to employ raycasting from the camera in order to choose specific items

Hi everyone, I'm currently attempting to create a ray that extends straight out from the camera and intersects with objects in my line of sight. However, all the resources I've come across involve using the mouse for this interaction, and I' ...

Enhancing JQuery UI Accordion with simple ICONS

Is it necessary to use the Jquery CSS file for adding icons, or is there an alternative method? I'm hoping I can avoid using it as I am working within Wordpress and enqueuing the Jquery CSS seems like a complex task for me. Apologies for the basic q ...

Eliminate any duplicate items from the array containing objects

I've been struggling with this issue for a week now, hopefully someone here can help me out... The application I'm working on was created using Laravel with Vue for the frontend. Essentially, I have an array of objects that need to be sent to t ...

Connect individuals based on specific criteria within a nested array

My MongoDB collection looks something like this: _id: ObjectId("5cb089e459552d8b8cc6a9e4") username: "admin" password: "12345" gender: "male" interestedIn: "female" movie: Array 0: Object id: "Avatar" title: "Avatar" poster: "~" 1: Object ...

Can you style a radio button input using only CSS without a label?

<input id="customize1" class="customize1" name="test" type="radio" checked="checked"> <input id="customize2" class="customize2" name="test2" type="radio"> Can these two elements be styled without directly targeting their labels, using only CSS ...

Resolving the issue with unique ids in Material UI Autocomplete

I have a situation where I need to assign unique IDs to my data entries, but I am struggling to find the correct place to include "key={id}". <AutoCompleteComp data={data} setInputValue={setInputValue} inputValue={inputVa ...

Guide to selecting multiple rows at once using ng-options in a list

Need assistance with an HTML list: I have a box displaying a list where users can select multiple items to save. The saving and retrieving process is functional as the selectedList stores the user's previous selections, while fullList contains all av ...

Exploring the Enzyme library in React to trigger an onClick event with a specific parameter

In my quest to simulate an onClick method in my unit tests using Enzyme for React, I have encountered various tutorials on simulating an onClick event that takes an event e. For example: handleClick(e) { // Does something } .... <MyComponent onCli ...

Can you explain the process of variable allocation?

I have a query regarding the following JavaScript code snippet. It might be a basic question, but I'm seeking clarification. // 'response' contains JSON data received from the backend: ....then(response => { this.myVar = response.data; ...

When CSS Display table is resized at media query breakpoints, it causes other cells to disappear

This is a discussion on creating a responsive image gallery website with images of different sizes and no margins or paddings. The issue at hand is that the .showcase class hides at a specific @media breakpoint when resizing, but there is a desire to displ ...

Retrieving input value in an Android WebView

I recently attempted to extract the value of an input type and store it as a string within my Android WebView. Unfortunately, I couldn't find a straightforward solution. The snippet of code in my HTML file is as follows: <input class="input100 ...

Establish a connection to AWS by utilizing MQTT.js

Looking to create a web page that connects to an AWS server? While python-Paho-mqtt allows for the use of tls_set to add security certificates and more, how can we achieve the same with MQTT.js? And if unable to do so, what are the steps to run python-PAHO ...

Creating a formatted JSON string from the data retrieved using a GET request and embedding it into an HTML template to be sent as the

Struggling to send JSON data retrieved from a GET METHOD as an email. The challenge is defining the body of the email using the obtained JSON object. Looking for solutions! Below is a snippet of my code: app.get('/userinfo',(req,res)=>{ ...

What sets `isomorphic-fetch` apart from `isomorphic-unfetch` in the world of npm packages?

Both Isomorphic Unfetch and Isomorphic Fetch are used for server-side rendering. But what sets them apart? Aside from the fact that Isomorphic Fetch is older and slightly larger when gzipped according to this comparison. Learn more about each library here ...

Challenges encountered when attempting to send an array in res.json with the MERN stack

I am facing a challenge while trying to make two separate model calls using the MERN stack. The issue arises when I try to send an array in res.json; extracting the data seems to be problematic. On examining the console log: {data: "[]", status: ...

Tips on accessing close autoComplete/TextField title in AppBar

Looking to add a search bar and login button in the AppBar, where the search Bar is positioned close to the title. The desired order for the AppBar components should be as follows: Title SearchBox LoginButton How can this be achieved? Below is th ...

What is the best approach to dynamically retrieve an API route from a component within the page directory?

I am encountering a problem with my reusable contact form. It functions perfectly when used in the index.js file, but when I try to use it from a component in the page folder, I receive a 404 not found error message. This is because it tries to access the ...

Error message displaying that the argument for the onChange state in a jhipster react form is not assignable as type '{ [x: number]: any; }'

Just diving into the world of React and encountering a bit of a struggle with jsx when it comes to setting state in a form that contains two fields and triggers an ajax call to store a json object (response data) in the state's field3. The code I curr ...