skip to Main Content

I am having file structure like this:

├── books
    ├── reviews
        ├── [title].jsx <- want to route here 
│   └── page.jsx
└── page.jsx

On the /books page I generate a list of books, each of it it’s has it’s own button to redirect to the review page of this book. For example books/reviews/nextjsbook

When I try to open any review page using: /books/reviews/[title] I get 404 error.

2

Answers


  1. I think you are using latest next.js 13 App router version
    You Should update your folder structure like this

    ├── books
        ├── reviews
            ├── [title]
                ├──page.jsx
    │   └── page.jsx
    └── page.jsx
    

    enter image description here

    Login or Signup to reply.
  2. When you try to navigate to this route directly (i.e., by entering the URL in the browser), It will not be able to find the file because it’s looking for a file named [title].jsx inside the reviews directory. This is why you’re getting a 404 error.

    Therefore, I suggest to use the Link component from next/link for navigation and the useRouter hook from next/router to access the dynamic route parameter.

    Example:

    import Link from 'next/link';
    import { useRouter } from 'next/router';
    
    export default function BookList({ books }) {
     const router = useRouter();
    
     return (
       <div>
         {books.map((book) => (
           <Link href={`/books/reviews/${book.title}`} key={book.title}>
             <a>{book.title}</a>
           </Link>
         ))}
    
         {router.query.title && (
           <div>
             <h1>{router.query.title}</h1>
             <p>This is the review page for {router.query.title}.</p>
           </div>
         )}
       </div>
     );
    }
    

    Link is used to create a link to the review page for each book. Then, the href prop is set to the path for the review page, and the book title is included as a dynamic segment.

    The useRouter hook is used to access the dynamic route parameter if the title query parameter is present in the URL, a div is rendered with the title and a message.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search