最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use slug url in nextjs - Stack Overflow

programmeradmin4浏览0评论

I am working in nextjs, i am trying to make "dynamic routes", i want after click my url should be like "myurl/article/55"

for this i use following "link tag"

<Link href={{pathname: "article/[id]",query: { id: post.id },}}>
            <a className="rdmre-btn"> Read More</a>
</Link>

And here is my code in ("pages/article/[slug].js) in file,Where i am wrong ? i want whenever i click on any blog then blog details page should open.

import Axios from "axios";
import { useRouter } from "next/router";
import Link from "next/link";
import LatestBlogs from "../../components/LatestBlogs/LatestBlogs";

const Post = ({ post }) => {
  const router = useRouter();
  const htmlString = post.description_front;
  if (router.isFallback) {
    return <div>Loading...</div>;
  }

  return (
    <>
      <header className="bgbanner blog_header">
        <div className="container cont">
          <div className="header">
            </div>
           </div>
        <div className="container "></div>
      </header>
      <section>
        <div className="container Blog_page_sidebar">
          <div className="blog_details">
            <div className="blog_image">
              <img src={post.image} />
            </div>
            <div className="blog_heading">
              <h2>{post.title}</h2>
            </div>
            <div className="blog_detail">
              <div
                className="product-des"
                dangerouslySetInnerHTML={{ __html: htmlString }}
              />
            </div>
          </div>
   
        </div>
      </section>
      </>
  );
};

export default Post;

export const getStaticProps = async ({ params }) => {
  const { data } = await Axios.get(
    `/${params.id}`
  );
  const post = data;
  return {
    props: {
      post,
    },
  };
};

export const getStaticPaths = async () => {
  const { data } = await Axios.get(
    "myurl/admin-panel/api/blogs"
  );
  const posts = data.slice(0, 10);
  const paths = posts.map((post) => ({ params: { id: post.id.toString() } }));
  return {
    paths,
    fallback: true,
  };
};

I am working in nextjs, i am trying to make "dynamic routes", i want after click my url should be like "myurl.com/article/55"

for this i use following "link tag"

<Link href={{pathname: "article/[id]",query: { id: post.id },}}>
            <a className="rdmre-btn"> Read More</a>
</Link>

And here is my code in ("pages/article/[slug].js) in file,Where i am wrong ? i want whenever i click on any blog then blog details page should open.

import Axios from "axios";
import { useRouter } from "next/router";
import Link from "next/link";
import LatestBlogs from "../../components/LatestBlogs/LatestBlogs";

const Post = ({ post }) => {
  const router = useRouter();
  const htmlString = post.description_front;
  if (router.isFallback) {
    return <div>Loading...</div>;
  }

  return (
    <>
      <header className="bgbanner blog_header">
        <div className="container cont">
          <div className="header">
            </div>
           </div>
        <div className="container "></div>
      </header>
      <section>
        <div className="container Blog_page_sidebar">
          <div className="blog_details">
            <div className="blog_image">
              <img src={post.image} />
            </div>
            <div className="blog_heading">
              <h2>{post.title}</h2>
            </div>
            <div className="blog_detail">
              <div
                className="product-des"
                dangerouslySetInnerHTML={{ __html: htmlString }}
              />
            </div>
          </div>
   
        </div>
      </section>
      </>
  );
};

export default Post;

export const getStaticProps = async ({ params }) => {
  const { data } = await Axios.get(
    `https://myurl.com/api/blogbyids/${params.id}`
  );
  const post = data;
  return {
    props: {
      post,
    },
  };
};

export const getStaticPaths = async () => {
  const { data } = await Axios.get(
    "myurl.com/admin-panel/api/blogs"
  );
  const posts = data.slice(0, 10);
  const paths = posts.map((post) => ({ params: { id: post.id.toString() } }));
  return {
    paths,
    fallback: true,
  };
};
Share Improve this question edited Jul 4, 2022 at 11:32 amit asked Jul 4, 2022 at 11:26 amitamit 1,2092 gold badges20 silver badges39 bronze badges 8
  • The file directory should be pages/article/[slug].js – User456 Commented Jul 4, 2022 at 11:28
  • @User456 you mean in "link" tag ?? – amit Commented Jul 4, 2022 at 11:29
  • @User456 you mean link href should be "pages/article/[slug].js" , am i right ? – amit Commented Jul 4, 2022 at 11:30
  • No, not the link href. The file should be in pages/article/ directory – User456 Commented Jul 4, 2022 at 11:31
  • @User456 file already in that folder (updated my question) – amit Commented Jul 4, 2022 at 11:32
 |  Show 3 more comments

2 Answers 2

Reset to default 9

In Next 14 you'll want to use useParams as this will give you the variables/slug in the URL. https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes

import { useParams } from "next/navigation";
const Post = () => {
  // folder structure /posts/[pid]
  const params = useParams();
  // example URL /posts/123
  const { pid } = params;
  // pid will equal 123
  return <p>Post: {pid}</p>
}

export default Post

[slug] is used to have nested routes. But correct is [...slug].js (info)

Example: myurl.com/article/[id]/[otherid]

In the example above we can see that in [id] can be nested children. You can name this param as you want.

If you want to have your structure as myurl.com/article/55, you need to have structure as follow:

In your pages folder:

  1. You create a folder article (pages/article)
  2. You create 2 files: index.js (or .tsx) and [id].js (you can name as [slug].js or [specialId].js - no matter the name
  3. After, you are getting info with param name created.

Here is example of the code (URL: myurl.com/article/55; file: pages/article/[pid].js)

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  //same name as name of your file, can be [slug].js; [specialId].js - any name you want
  const { pid } = router.query
  //result will be '55' (string)
  return <p>Post: {pid}</p>
}

export default Post
发布评论

评论列表(0)

  1. 暂无评论