programming

Layouts for NextJs Website

Steps detailing how to set up persistent per-page layout for NextJs website while using Typescript

21st December 2021

·

1 Min Read

Cover Photo

Persistent layouts are important, so your site does not have to re-render the entire document every time the URL is changed.

 

NextJs by default re-renders the entire UI every time a link is clicked. NextJs does have documentation on how to implement shared layout, but I still found it tricky to follow when using Typescript.

 

Code for shared layout

Modify _app.tsx

Adding getLayout to your page allows React component to set the layout.

1// /pages/_app.tsx
2
3import React from 'react';
4
5import type { ReactElement, ReactNode } from 'react';
6import type { NextPage } from 'next';
7import type { AppProps } from 'next/app';
8
9type NextPageWithLayout = NextPage & {
10    getLayout?: (page: ReactElement) => ReactNode;
11};
12
13type AppPropsWithLayout = AppProps & {
14    Component: NextPageWithLayout;
15};
16
17const MyApp: ReactNode = ({ Component, pageProps }: AppPropsWithLayout) => {
18    const getLayout = Component.getLayout ?? ((page: ReactNode) => page);
19
20    return <>{getLayout(<Component {...pageProps} />)}</>;
21};
22
23export default MyApp;
24

 

Modify page component

This is sample code of how I added layout to my Homepage component. Modify to your own use case.

 

1// /pages/index.tsx
2
3import React, { FC } from 'react';
4import { GetStaticProps } from 'next';
5
6import type { ReactNode, ReactElement } from 'react';
7
8import { AppLayout } from '@Components/AppLayout';
9
10// this function can be skipped if no data needs to be fetched
11export const getStaticProps: GetStaticProps = async () => ({
12    props: {
13        homepageData: await getPageData('homepage')
14    }
15});
16
17// if component does not need props use FC instead of FC<{ homepageData: IHomepageData }>
18const Homepage: FC<{ homepageData: IHomepageData }> & { getLayout: ReactNode } = ({ homepageData }) => {
19  return (<></>);
20};
21
22// sets up layout of page
23Homepage.getLayout = (page: ReactElement) => {
24  
25    // only use if prop data is needed to modify layout 
26    const data = page.props.homepageData;
27
28    return (
29        <AppLayout>
30            {page}
31        </AppLayout>
32    );
33};
34
35export default Homepage;
36

 

Conclusion

Using the above code can be used to add per-page layout easily throughout your website.

 

 

Please disable adblock


Tags:

NextJsWebsiteLayoutTypescript