I'm using Next.js and created 3 pages.
I want to give the user some attention whenever the user will go to the new page. For this, I have added the library name NProgress which shows a loading line on the top of the viewport. The logic of NProgress is written inside the pages/_app.js
file.
_app.js:
import React from 'react';
import Router from 'next/router';
import NProgress from 'nprogress';
NProgress.configure({
speed: 800,
showSpinner: false,
});
Router.events.on('routeChangeStart', () => {
NProgress.start();
});
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp;
The loading line is working fine whenever I change the route and go to the categories
page.
But When I change the route by clicking on any categories
which redirects to the categories/[slug].js
page. The loading line is shown for small seconds and then it is hidden.
You can see it.
Is there a way we can resolve this issue?
pages/index.js
:
import React from 'react';
import Link from 'next/link';
export default function Home() {
return (
<div>
<Link href="/categories">
<a>Categories</a>
</Link>
<Form>
<Button />
</Form>
</div>
);
}
pages/categories/index.js
:
import React from 'react';
import Link from 'next/link';
export default function Categories() {
return (
<div>
<div className="categories">
<ul>
<li>
<Link href="/categories/wordpress" as="/categories/wordpress">
<a>Wordpress</a>
</Link>
</li>
<li>
<Link href="/categories/magento" as="/categories/magento">
<a>Magento</a>
</Link>
</li>
<li>
<Link href="/categories/drupal" as="/categories/drupal">
<a>Drupal</a>
</Link>
</li>
<li>
<Link href="/categories/shopify" as="/categories/shopify">
<a>Shopify</a>
</Link>
</li>
</ul>
</div>
</div>
);
}
pages/categories/[slug].js
:
import React from 'react';
export default function CategoryPage(props) {
const { slug } = props;
return (
<h1>Hello - { slug }</h1>
);
}
CategoryPage.getInitialProps = async (context) => {
const categorySlug = context.query.slug;
return {
slug: categorySlug
};
};
The 2nd link click is cause to hard reload the page. When you click on the 2nd time you can see the spinning icon on the browser tab.
Can you try to define your links like this ?
<Link href='/categories/[slug]' as="/categories/wordpress">
<a>wordpress</a>
</Link>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With