Skip to content

Instantly share code, notes, and snippets.

@dstreet
Last active August 27, 2021 08:33
Show Gist options
  • Save dstreet/7642b229e33f3cfe137dd7f3bae7a37d to your computer and use it in GitHub Desktop.
Save dstreet/7642b229e33f3cfe137dd7f3bae7a37d to your computer and use it in GitHub Desktop.
Example HOC with Next.js
import React from 'react'
/*
* Higher order component that passes `getInitialProps` through
* to the child component
*/
const HOC = function(Child) {
return class Higher extends React.Component {
static getInitialProps(ctx) {
return Child.getInitialProps(ctx)
}
}
}
/*
* Child component
*/
const class MyComponent extends React.Component {
static getIntialProps({ req }) {
// Do something asynchronously...
// Not strickly necessary. Just an example
const promise = new Promise((resolve, reject) => {
setTimeout(() => res(), 500)
})
return promise.then(() => ({ initialState: { foo: 'bar' }, isServer }))
}
render() {
return <h1>Hello, World</h1>
}
}
export default HOC(MyComponent)
@dstreet
Copy link
Author

dstreet commented Apr 4, 2020

This was a quick example of an initial props pass through. It was made for a really old version of Next.js. Mileage may vary with newer versions

@heshamelmasry77
Copy link

for example a private route for your app

const PrivateRoute = (AuthComponent) => {
  return class Higher extends React.Component {
    static async getInitialProps(ctx) {

      const pageProps =
        AuthComponent.getInitialProps &&
        (await AuthComponent.getInitialProps(ctx))
      // Return props.
      return { ...pageProps }
    }

    render() {
      return <AuthComponent {...this.props} />;
    }
  };
};
export default PrivateRoute;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment