utilizing a reusable design in the nextjs directory for pages

If I have the following files in my /pages directory and want to utilize the same template for cats/[slug] and dogs/[slug] routes (excluding fish), what steps should I take? Currently, I am duplicating the file...

  index.js
  cats.js
  dogs.js
  fish.js
    /cats
      [slug].js
    /dogs
      [slug].js
    /fish
      [slug].js

Answer №1

One way to create a reusable component is by defining it in the components directory and then using it accordingly.

components/Pet.jsx

const Pet = () => {
  // write your component logic here
};

export default Pet;

pages/dogs/[slug].jsx

import Pet from '../components/Pet';

const Dog = () => {
  return (
    <Pet type="dog"
      {...otherProps}
    />
  );
};

export default Dog;

Answer №2

Although this question may be dated, a solution is to utilize "Dynamic Routes." Predefined routes take precedence over dynamic routes in this case. To make dynamic routes compatible with statically generated pages, the slug page must specify a list of paths using getStaticPaths.

To ensure a unique page under fish, you must explicitly define that page or set up a different "[slug]" page under a fish directory.

Hence, cats.js, dogs.js, fish.js will render at domain.com/cats/, domain.com/dogs/, domain.com/fish/. Dynamic routes will match at domain.com/cats/athing/, domain.com/dogs/anotherthing/, domain.com/fish/anythingelse/, etc...

getStaticPaths requires two parameters matching the name of the dynamic path directory and slug.


Create a "dynamic" directory at the top level of the pages directory for the animal route and include the slug inside like:

[animal]/[slug].js

The structure should resemble this in the pages directory:

 index.js
 cats.js
 dogs.js
 fish.js
 [animal]/[slug].js

In [slug].js, getStaticPaths needs to pass both the [animal] and [slug] values to create content only accessible under specific top-level pages.

A simplified static example could be:

export async function getStaticPaths() {
  return {
    paths: [
        { params: { animal: 'cats', slug: 'athing' } },
        { params: { animal: 'dogs', slug: 'anotherthing' } },
        { params: { animal: 'fish', slug: 'anythingelse' } }
    ],
    fallback: false, // can also be true or 'blocking'
  }
}

An example in Typescript with data fetching might look like this, where getAllSlugPathsWithAnimal returns an array of objects as follows:

{ animal: 'dogs', slug: 'anotherthing'}

export const getStaticPaths: GetStaticPaths = async () => {
  const slugPathsWithAnimal: AllSlugPathsWithAnimal[] = await getAllSlugPathsWithAnimal();

  const paths = slugPathsWithAnimal.map((slugAndAnimal) => ({
    params: { animal: slugAndAnimal.animal, slug: slugAndAnimal.slug },
  }));

  return {
    fallback: false,
    paths,
  };
};

For more information on dynamic routes: https://nextjs.org/docs/routing/dynamic-routes For details on data fetching: https://nextjs.org/docs/basic-features/data-fetching/get-static-paths

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

Fetch data from Firestore when the page loads using the useEffect hook

Below is the simplified code snippet I am currently using: import { useState, useEffect, useContext } from 'react' import { useRouter } from 'next/router' import { firestore } from './firebase-config' import { getDoc, doc } f ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

No data is being retrieved by SWR

I'm struggling to make SWR work in my code. Despite trying multiple examples, I can't seem to get it functioning properly. It's frustrating because the code looks fine and should work. I feel like I must be missing something simple. Current ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

What is the correct way to use getServerSideProps?

Lately, I've been exploring the world of web development by creating a web app using NextJS. While I have some knowledge of the basics in this field, I found myself a bit lost when working with NextJS since I hadn't worked with React before. One ...

Encountered an error during the production build of NEXTJS, where it panicked due to the global thread pool not being initialized

While hosting my app on Heroku and running git push heroku main, I encountered the following error: panicked at 'the global thread pool has not been initialized.: threadpool builderror { kind: ioerror(error { kind: unsupported, message: "operatio ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...

Dates comparison causing Firestore security rules issue

After running the query shown below, I encountered a permission-denied message with an error in the "Monitor rules" tab. const timeNow = useMemo(() => Timestamp.now(), []); const query = query( postRef, where("tags", "array-contai ...

Is it possible to incorporate a next.js image onto the background design?

I've encountered an issue while attempting to create a fixed background image with a parallax effect using Tailwind CSS and Next.js Image. If you need to see an example of this in action, check out this Template Monster theme. Here's the code s ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...

Guide to finding and saving email addresses from a string output: extracting and storing each one individually in a text file

After collecting data from multiple sources, the output I obtained is as follows: "addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main- ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

nextAuth.js is failing to access the accessToken, returning only the values {iat, exp, jti} instead

Here is the code I am working with: import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" export default NextAuth({ sectret:process.env.NEXTAUTH_SECRET, session: { strategy: "jw ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

What steps do I need to take to ensure NextJS stores my edits in VSCode?

I have attempted various troubleshooting steps such as changing file extensions from .js to .jsx, turning on Prettier for formatting upon saving, setting it as the default formatter, reloading and restarting the editor. However, the issue with not being ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

"Encountering difficulties while trying to modify the QuillNoSSRWrapper value within a Reactjs

Currently, I am working on a project involving ReactJS and I have opted to use the Next.js framework. As of now, I am focused on implementing the "update module" (blog update) functionality with the editor component called QuillNoSSRWrapper. The issue I ...