Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to write a Next.js router proxy? #766

Closed
zalbia opened this issue Jul 23, 2018 · 3 comments
Closed

How to write a Next.js router proxy? #766

zalbia opened this issue Jul 23, 2018 · 3 comments

Comments

@zalbia
Copy link

zalbia commented Jul 23, 2018

A proxy is already available for react-router but missing out-of-the-box for next.js' built-in router. I've tried using react-cosmos-wrapper-proxy and fiddled around with wrapping my component with next.js <Container> but that didn't do it.

Just to get a component working on cosmos that uses next's <Link>, I've had to mock out the router like so:

import Router from 'next/router'

const mockedRouter = { push: () => {}, prefetch: () => {} }
Router.router = mockedRouter

This isn't ideal and is probably not the cosmos way. I would like to be able to test the routing too.

@ovidiuch
Copy link
Member

@zach-albia You're pretty close to viable solution. It seems the Next.js Links call a global Router singleton. So I believe overriding Router/router is the way to go.

Here's a (untested) draft of what the proxy would look like:

class NextProxy extends Component {
  constructor(props) {
    super(props);

    this.__realRouter = Router.router;
    Router.router = createRouterMock();
  }

  componentWillUnmount() {
    if (this.__realRouter) {
      Router.router = this.__realRouter;
    }
  }

  render() {
    const { nextProxy, ...rest } = this.props;
    const { value: NextProxy, next } = nextProxy;

    return <NextProxy {...rest} nextProxy={next()} />;
  }
}

function createRouterMock() {
  // This will probably evolve in time
  return { push: () => {}, prefetch: () => {} };
}

@zalbia
Copy link
Author

zalbia commented Jul 25, 2018

Interesting, I'll try it out. I wonder how we can make a suitable mock. I'll try to see what I can do on that front. I'm also hoping someone with some knowledge of next.js' internals can chime in.

xavxyz added a commit to xavxyz/nextjs-page-transitions that referenced this issue Aug 15, 2018
xavxyz added a commit to xavxyz/nextjs-page-transitions that referenced this issue Sep 3, 2018
@ovidiuch
Copy link
Member

ovidiuch commented May 6, 2019

Discussion belongs to http://github.com/react-cosmos/react-cosmos-classic.

I'd be happy to discuss Next.js integration with Cosmos Next if anybody has issues.

@ovidiuch ovidiuch closed this as completed May 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants