I'm new to nextjs and trying to list out blogs and on click of blog, the page with dynamic URL blog/[slug].js should load, but the use of Link and Router.push(") reloads the page.
blogs.js
import Link from 'next/link';
const renderBlogs = (blogs) => {
return blogs.map(blog => <Link href={`/blog/${blog.slug}`}>
<a key={blog.id}>{blog.title}</a>
</Link>
)
}
function Myblogs(props) {
let blogs = [
{ id: 1, title: "blog 1", slug: "blog-1" },
{ id: 2, title: "blog 2", slug: "blog-2" }
]
return renderBlogs(blogs);
}
export default Myblogs;
blog/[slug].js
import { useRouter } from 'next/router'
const SingleBlog = (props) => {
const router = useRouter()
const slug = router.query.slug
return <>
<h3>Single Blog</h3>
<p>{slug}</p>
</>
}
export default SingleBlog
I'm trying to load [slug].js without reloading but somehow Link causes the page to reload. Thanks in advance.
Missing the as
prop for the Link
component. Required for dynamic pages.
...etc
const renderBlogs = blogs => (
blogs.map(({ id, slug, title }) => (
<Link key={id} href="/blog/[slug]" as={`/blog/${slug}`} >
<a>{title}</a>
</Link>
)
);
...etc