Next.js Discord

Discord Forum

Do Layouts get Params?

Answered
Common paper wasp posted this in #help-forum
Open in Discord
Common paper waspOP
I'm working on setting up my blog post layout and page and have this layout right now

import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function BlogPostLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <article className="prose prose-headings:text-neutral-300 text-neutral-200 container max-w-4xl">
      {children}
    </article>
  );
}


And I recently moved the article into my slug page.tsx but now may want to move the actual layout of it back here and just render

    <>
      <div dangerouslySetInnerHTML={{ __html: post.content }}></div>
    </>


Into my page as the child(ren). But the only thing is my slug pages use Velite to get data about the slug by using params

import { notFound } from "next/navigation";
import { getPostBySlug } from "@/app/lib/utils";

export default function BlogPost({ params }: { params: { slug: string } }) {
  const post = getPostBySlug(params.slug);

  // If the blog post requested does not exist, throw a 404 using Next's notFound function - neat!
  // https://nextjs.org/docs/app/api-reference/functions/not-found
  if (post == null) notFound();

  return (
    <>
      <div dangerouslySetInnerHTML={{ __html: post.content }}></div>
    </>
  );
}


So can I use Params like this in a layout?
Answered by joulev
app/blog/
  layout.tsx
  [slug]/
    layout.tsx
    page.tsx

the first layout file does not know the value of slug.

the second layout file knows the value of slug, you can retrieve it by using the params prop: https://nextjs.org/docs/app/api-reference/file-conventions/layout#params-optional
View full answer

4 Replies

Common paper waspOP
I'll add that the docs don't seem to indicate this is possible but wanted to ask

https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts
app/.../[a]/
  layout.tsx <- 1
  [b]/
    layout.tsx <- 2
    page.tsx <- 3


1, 2 and 3 all get access to a
only 2 and 3 get access to b
Common paper waspOP
Sorry I dont follow
app/blog/
  layout.tsx
  [slug]/
    layout.tsx
    page.tsx

the first layout file does not know the value of slug.

the second layout file knows the value of slug, you can retrieve it by using the params prop: https://nextjs.org/docs/app/api-reference/file-conventions/layout#params-optional
Answer