0

I have a component that is receiving data:

const ProductTile = ({ data }) => {
  let { productList } = data
  var [products] = productList
  var { products } = products;
  return (
    <div>
      <div className="p-10 grid grid-cols-1 sm:grid-cols-1 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 gap-5">

        {products.reduce((products, product) => products.find(x => x.productId === product.productId) ? products : [...products, product], []).map(({ colorCode, defaultColorCode, now, productId, productCode, productDescription, }, index) => {
            return (
              <Link key={`${productId}${index}`}
                href={{
                  pathname: '/s7-img-facade/[slug]',
                  query: { slug: productCode },
                }}
                passHref>
                  /* template */
              </Link>
            )
          })}
      </div>
    </div>
  )
}

export default ProductTile

It creates a grid of templates each wrapped in a <Link> component which is rendering a dynamic component;

/s7-img-facade/[product]

What I would like is for the dynamic component to have access to products object which is in the ProductTile .

I know that I can do a getStaticProps in the dynamic component to do another request but that seems redundant and not dry...

Any ideas how the dynamic component get access to the products object?

Thanks in advance!

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141

1 Answers1

1

You've got the right idea - you can pass additional properties in the query field, but you'll need to use getServerSideProps to extract those from the query param and pass it to the page component as props. Something like this:

// pages/product.js
...
  <Link key={`${productId}${index}`}
    href={{
      pathname: '/s7-img-facade/[slug]',
      query: {
        description: productDescription, 
        slug: productCode
      },
    }}
    passHref
  >
    /* template */
  </Link>
...

// pages/s7-img-facase/[slug].js
export default function S7ImgFacasePage({ description }) {
  return <p>{ description }</p>
}

export const getServerSideProps = ({ params }) => {
  const description = { params }
  return {
    props: {
      description
    }
  }
}

So basically you pass it from the first page in params, read that in getServerSideProps of the second page, and then pass that as a prop to the second page component.

You mentioned getStaticProps - this won't work with static pages because getStaticProps is only run at build time so it won't know anything about the params you send at run time. If you need a fully static site, then you should consider passing it as a url parameter and reading it in useEffect or passing all possible pages through getStaticPaths and getStaticProps to generate all your static pages.

I'm Joe Too
  • 5,468
  • 1
  • 17
  • 29