Skip to content

Instantly share code, notes, and snippets.

@djmarland
Created May 21, 2020 18:03
Show Gist options
  • Save djmarland/da31b8c4b8f6ec2a5089260146228426 to your computer and use it in GitHub Desktop.
Save djmarland/da31b8c4b8f6ec2a5089260146228426 to your computer and use it in GitHub Desktop.
How to do HOCs in NextJS?
export const AppContainer = (Page: any) => {
return class extends Component {
public static async getInitialProps(context) {
let initialProps = {
appData: getAppData,
pageData: {},
}
if (Page.getInitialProps) {
initialProps.pageData = await Page.getInitialProps(context);
}
return initialProps;
}
public render() {
const { appData, pageData } = this.props;
return (
<AppWrapper data={appData}>
<Page {...pageData} />
</PlayContainer>
);
}
};
};
export class Page extends Component {
public static async getInitialProps({ req, res }) {
const data = await getData(req, res);
return {
data,
};
}
public render() {
return <MainPage {...this.props}/>;
}
}
export default AppContainer(Page);
Up until now I've been making good use of Higher Order Componets (HOC) in NextJS. My page might look like Page.jsx and the AppContainer would be like AppContainer.jsx.
This is very useful for having a common wrapper around the page.
However `getServerSideProps` doesn't seem to support this pattern since it is exported directly, and the Page is an independent export.
The only suggestion I've seen is to use _app.jsx, but that is global. Some pages I don't want to have this AppWrapper. And some pages have a different HOC wrapper.
I like the idea of `getServerSideProps`, so would like to use it if I can figure out how to retain this functionality. Can anyone suggest a new pattern that would solve it? Thanks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment