Theo's Typesafe CultTTC
Theo's Typesafe Cult4y ago
18 replies
Mike Farad

Per-Page Layouts in T3

Hey guys I was attempting to implement per page layouts on the t3 starter template as shown here:
https://nextjs.org/docs/basic-features/layouts#with-typescript


I kept running into Typescript issues. Any way I could go about this in a way I could make Typescript happy?
There is a squiggly line on MyApp and the getLayout function argument in the return.

Feel free to suggest a better approach for this.


// pages/_app.tsx
import type { AppProps } from "next/app";
import { type AppType } from "next/app";
import { type Session } from "next-auth";
import { SessionProvider } from "next-auth/react";

import { trpc } from "../utils/trpc";

import "../styles/globals.css";
import type { NextPage } from "next";
import type { ReactElement, ReactNode } from "react";


export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
  getLayout?: (page: ReactElement) => ReactNode;
};

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout;
};

const MyApp: AppType<{ session: Session | null }> = ({
  Component,
  pageProps: { session, ...pageProps },
}: AppPropsWithLayout) => {
  const getLayout = Component.getLayout || ((page: NextPage) => page);

  return getLayout(
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
};

export default trpc.withTRPC(MyApp);


// pages/index.tsx
import type { ReactElement } from "react";
import Layout from "../components/Layout/Layout";
import type { NextPageWithLayout } from "./_app";

const Home: NextPageWithLayout = () => {
  return (
    <>
      <div>Hello</div>
    </>
  );
};

Home.getLayout = function getLayout(page: ReactElement) {
  return <Layout>{page}</Layout>;
};

export default Home;
Learn how to share components and state between Next.js pages with Layouts.
Basic Features: Layouts | Next.js
Was this page helpful?