next-routes icon indicating copy to clipboard operation
next-routes copied to clipboard

Unable to access current route name in component

Open shift-keshav-pudaruth opened this issue 6 years ago • 7 comments

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 avatar Jun 11 '18 09:06 shift-keshav-pudaruth

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.

shift-keshav-pudaruth avatar Jun 11 '18 09:06 shift-keshav-pudaruth

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

TrebuhD avatar Jun 12 '18 22:06 TrebuhD

Agreed, thanks @shift-keshav-pudaruth!

michaeljonathanblack avatar Jun 17 '18 03:06 michaeljonathanblack

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

martpie avatar Jul 11 '18 12:07 martpie

@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 avatar Sep 01 '18 00:09 zenflow

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

fridays avatar Sep 02 '18 16:09 fridays

@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?

elisechant avatar Feb 28 '19 02:02 elisechant