fridays / next-routes

Universal dynamic routes for Next.js
MIT License
2.47k stars 230 forks source link

Unable to access current route name in component #190

Closed shift-keshav-pudaruth closed 1 year ago

shift-keshav-pudaruth commented 6 years ago

Since this.props.url is deprecated, we can no longer access the route's name through the props of the component.

If you append the name of the current route through server.js, it will stop working during client-side routing.

Inspecting the Router object shows that the 'name' of the route is not being appended anywhere, hence the withRouter solution described in the deprecated page fails too.

shift-keshav-pudaruth commented 6 years ago

Solution

We extend our _app.js file and inject the url props to allow it to work as before:

import React from 'react';
import Routes from '../routes';

class MyApp extends App {
    static async getInitialProps ({ Component, ctx }) {
        let pageProps = {};

        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx);
            pageProps.url = Routes.match(ctx.asPath);
        }

        return {pageProps}
    }

    render () {
        const {Component, pageProps} = this.props;
        return (
            <Container>
                        <Component {...pageProps} />
            </Container>
        )
    }
}

Then access the url props directly in your pages. Name of the route will be found at this.props.url.route.name.

Hopefully, this solution will solve a few headaches. Been stuck on this one for the past hour.

TrebuhD commented 6 years ago

I stumbled upon this post after an hour of scratching my head. Thanks for this solution @shift-keshav-pudaruth !

michaeljonathanblack commented 6 years ago

Agreed, thanks @shift-keshav-pudaruth!

martpie commented 6 years ago

TypeScript typings do not seem up-to-date as I get a Property 'match' does not exist on type 'Routes'. unfortunately.

https://github.com/fridays/next-routes/blob/master/typings/next-routes.d.ts#L47

zenflow commented 6 years ago

@fridays Would you review a PR to add the implementation for withRouter that works the same as the native version but includes the extra route info? It would be nice to be able to access the route info the same standard way as a vanilla next.js app.

fridays commented 6 years ago

Totally! I'm short on time at the moment but review asap. Thanks for contributing!

elisechant commented 5 years ago

@fridays Would you review a PR to add the implementation for withRouter that works the same as the native version but includes the extra route info? It would be nice to be able to access the route info the same standard way as a vanilla next.js app.

@zenflow what happened with this?