2

Let's say this is my pages/visitor.tsx

const PageQuery = 'my query';

const Visitor = () => {
  return <div>Hello, World!</div>;
};

export default Visitor;

How do I access PageQuery in _app.tsx?

It appears that one way to do it is by attaching PageQuery as a property to the component function, e.g.,

const PageQuery = 'my query';

const Visitor = () => {
  return <div>Hello, World!</div>;
};

Visitor.PageQuery = PageQuery;

export default Visitor;

Now inside of _app.tsx I can access it like so:

const App = ({ Component, pageProps }: AppProps) => {
  Component.PageQuery;
}

However, I was wondering if I am just overlooking a canonical way to access exports for every page when it is being loaded.

1 Answers1

1

Functions are first class objects in javascript. Any react functional component is just another function and it can have custom properties.

const Visitor = () => {
  return <div>Hello, World!</div>;
};
Visitor.PageQuery = 'my query';

export default Visitor;

Now you can make use of this in _app.tsx

const App = ({ Component, pageProps }: AppProps) => {
 const query = Component.PageQuery ?? '';
...

}
 

Note: You might face issue with Typescipt. TS is not aware of the property you have just added.

So you might need to extend the default types using & :

type NextPageWithQuery<P = {}, IP = P> = NextPage<P, IP> & {
  PageQuery?: string;
};
type AppPropsWithPageQuery = AppProps & {
  Component: NextPageWithLayout;
};

and accordingly this will change:

const App = ({ Component, pageProps }: AppPropsWithPageQuery) => {
 const query = Component.PageQuery ?? '';
...

}
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39