Using the below code, I see unexpected behavior in Javascript: When clicking on any items, the website navigates to lifestyle/[id]
, but it does not render correct content or it raises 404 error. Why is this happening?
Below is the content of components/lifestyle.jsx
:
import React from 'react';
import Link from 'next/link';
import _ from 'lodash';
const Lifestyle = ({ news }) => {
const sortedNews = _.sortBy(news, 'published_date').reverse();
return (
<div>
<h1 className="text-2xl sm:text-3xl text-center text-black font-bold p-1 rounded-xl">LifeStyle</h1>
{sortedNews.length > 0 && (
<div className='flex flex-col lg:flex-row justify-center p-2 lg:pr-3 gap-2 lg:border-r-2 border-gray-400'>
{sortedNews.slice(0,3).map((item, index) => (
<div key={index} className='flex flex-row lg:flex-col w-full lg:w-1/3 border-b-2 border-gray-300 '>
<Link href={`/${item.category}/${item.id}` } legacyBehavior>
<a>
<img src={item.image_url} alt={item.title} className='object-cover h-auto lg:h-36 w-4/6 lg:w-full p-1 rounded-lg' />
<h1 className='text-black w-2/6 lg:w-full p-2 font-bold text-2xl md:text-lg'>{item.title}</h1>
</a>
</Link>
</div>
))}
</div>
)}
</div>
);
};
export default Lifestyle;
// pages/[category]/[id].js
import { useRouter } from 'next/router';
const NewsItemPage = () => {
const router = useRouter();
const { id, category } = router.query;
return (
<div>
<h1>Hello World</h1>
<p>Category: {category}</p>
<p>News ID: {id}</p>
</div>
);
};
export default NewsItemPage;
Below is the local directories tree:
app
├── pages
│ ├── [category]
│ │ └── [id].js
├── components
│ ├── Lifestyle.jsx
│ └── // other components
├── api
│ └── news
│ └── route.js
└── // other files
I am trying to get the ID and category from the URL: http://localhost:3000/lifestyle/41
New contributor
Saniul Islam Sani is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.