I'm trying to rebuild my CRA Website with NextJS and I'm a little stuck on this page :
The middle container has 3 parts :
It works perfectly fine with CRA. So, with NextJS, I did the following : The list of index has, for each index item, a link component to, for example: "https://www.phidbac.fr/Liste-des-index/50"
,
and a file [id].js in pages/Liste-des-index folder :
// fetch List and Description on each new select
const Indexes = ({ listeIndex, cours, id }) => {
return (
<>
<Layout>
<PageIndex listeIndex={listeIndex} id={id} cours={cours} />
</Layout>
</>
);
};
export default Indexes;
Indexes.getInitialProps = async ({ req }) => {
// Get the correct ID Description from URL
let id = req.url;
id = id.split("/")[2];
const res = await fetch("https://www.phidbac.fr:4000/Indexes");
const dataList = await res.json();
const res1 = await fetch(`https://www.phidbac.fr:4000/Indexes/${id}`);
const dataDescription = await res1.json();
return {
listeIndex: dataList,
cours: dataDescription,
id: id
};
};
It's working, but this page does a complete reloading on each click, so it's slow and clearly not a good solution.
How can I achieve something as smooth as the CRA version ?
Thanks for helping :D
EDIT :
On this screenshot, you can see the delay between click and page loading, and the scroll container returning to the beginning.
I just try to don't refresh the index list on each click and just change the description from the right side.
I've edited the git with your solution if you wanna try.
Thanks again :)
The naming convention you are using for your [id-name].js
page, is part of the Dynamic routes feature of Next.js. By slightly modifying your code, using next/link
for Dynamic routes , I think I managed to achieve what you requested.
At first, you have to modify ListeIndex.tsx
and use Link
component from next/link
with props href
and as
(more about it on the link provided above and on the comments below)
// ListeIndex.tsx
import Link from 'next/link'
// const { Link } = routes;
...
<Link
key={element.id}
prefetch={false}
href="/Liste-des-index/[id-name]" // `href` points to page [id-name].js
as={`/Liste-des-index/${element.id}-${element.nom // `as` holds the data you need to pass
.replace(/\u202f/g, "-")
.replace(/\//g, "-")}`}>
...
Then, you just need to modify your [id-name].tsx
, and expect your data under query
instead of req
// [id-name].tsx
...
Indexes.getInitialProps = async ({ query }: any) => {
const id = query['id-name'].split("-")[0]; // you should find your data under `query` parameter
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.