Skip to content
Advertisement

NextJS render content from a different page

I’ve two routes like,

app/products => pages/products/index.js
app/products/1 => pages/products/[page].js

Here both app/products and app/product/1 will render the same content (same product items), is it possible to render app/products/1 content in app/products without writing duplicate code? I could find anything similar in their documentation.

Thanks.

Advertisement

Answer

The easiest way is to abstract the content from the page level. No need for tricky code here. pages/products/index.js:

import { ProductPageContent } from 'components/ProductPageContent';
import { getProductData } from 'lib/productData';

export default function ProductsIndexPage() {
  return <ProductPageContent />
}

export async function getStaticProps() {
  const productData = await getProductData();
  return {
     productData,
  }
}

pages/products/[page].js:

import { ProductPageContent } from 'components/ProductPageContent';
import { getProductData } from 'lib/productData';

export default function ProductPagePage() {
 return <ProductPageContent />
}

export async function getStaticProps() {
  const productData = await getProductData();
  return {
     productData,
  }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement