I am trying to create a global variable that all components are rendered with by default and set that default value but I'm not sure how to do the 2nd part. Here's what I have so far in my _app.tsx:
import { AppProps } from "next/app";
import type { NextComponentType } from 'next'
import Blue from "../components/blue";
type CProps = AppProps & {
Component: NextComponentType & {model?: string }
};
const MyApp = ({
Component,
pageProps: { ...pageProps },
}: CProps) => {
return (
<>
{Component.model === 'blue' ? (
<Blue>
<Component {...pageProps} />
</Blue>
) : (
<Component {...pageProps} />
)}
</>
);
};
But this obviously doesn't give me a default value for model. It just creates that variable with null value for all the components. How do I set the value?
Side question: Is this better done using React Context?
Edit 1: This is how the component sets the model value if it does not want to use the default value:
const ComponentFoo = () => {
return (
<>Test</>
);
};
ComponentFoo.model = 'red'
export default ComponentFoo;
This sounds like a good candidate for Next.js Layouts. You would have to compose a Layout component, similar to Blue in your example, which accepts a color prop and encapsulates the color rendering logic to the layout file. You can implement a default render path if no color prop is provided.
Then you can use it like so:
// pages/whatever.tsx
import type { ReactElement } from 'react'
import Layout from '../components/layout'
export default function Page() {
return {
/** Your content */
}
}
Page.getLayout = function getLayout(page: ReactElement) {
return (
<Layout color="blue">
{page}
</Layout>
)
}
https://nextjs.org/docs/basic-features/layouts#with-typescript