router5 / react-router5

Helpers for using router5 with React [MOVED]
MIT License
83 stars 8 forks source link

withRouter HOC #39

Closed jonaskello closed 6 years ago

jonaskello commented 6 years ago

withRoute HOC Will create a new component, injecting your router instance (from context) and the current route to the > > wrapped component. Any route change will trigger a re-render.

I think it could be useful to have a HOC that only injects the router that can be used in cases where you just want the router but are getting the route from Redux. Basically it would just inject the router from the context as a prop.

troch commented 6 years ago

Hi @jonaskello, this repo has been moved to the main router5 repo. A withRouter HOC can easily be added

jonaskello commented 6 years ago

Aha, ok I might re-post there. I'm not sure it is needed however. I was under the impression you needed the router in order to navigate but I I found that I can use the navigate action instead when using the redux integration. Might still be interesting when you don't use redux integration though.

troch commented 6 years ago

There are Link and BaseLink components available.

You can also create your own link component to navigate.You don't have to use a HOC to inject your router instance, you can define contextTypes directly.


class Link extends PureComponent {
    constructor(props, context) {
        super(props, context)
        this.router = context.router
    }

    render() {
        /* ... */
    }
}

Link.contextTypes = {
    router: PropTypes.object.isRequired
}
troch commented 6 years ago
jonaskello commented 6 years ago

Yes, I basically did a HOC that injected the router from the context. I use typescript and AFAIK contextTypes is not possible to type, so to use context I need to go through some tricks like casting to the component to any etc. Also you need to import the prop-types package in all components that use context. So basically it is just a convenience HOC to inject the router from context without going through the troubles of specifying contextTypes directly in the component.

But as you say I think for redux it is better to just use the store for everything.