Closed ctrlplusb closed 6 years ago
Sorry for late reply. There is currently no official api for it, there is only the internal .match
:
const routes = require('../routes')
...
static async getInitialProps({asPath}) {
console.log(routes.match(asPath))
}
It takes a URL, and returns everything you might need. But it's not official, so it might change in the future. What specific data would you like to receive, only the route name?
@fridays is this still the best way to do it?
it's shocking that a routing solution has no current route implementation :/ i managed to solve it by cascading down from the initial component as prop ... all the way until the component i need but this kind of defeats the purpose
Checkout withRouter to access the Router anywhere in your app
Just tried using withRouter
-- works for simple routes, but not with parameterized routes (at least that's what it seems like on the surface). @fridays it might be worth going over the various routing scenarios you support and test that withRouter can withstand them
Ignore my previous comment. Am able to get some parameterized routes to work so it’s likely something on my end.
@matb33 How do you use it with parameterized routes?
@omerdn1 withRouter will grab the router instance from context and you’ll have it as props in your component. The you should be able to get the value of a param, for example, like this: this.props.router.query.id (where :id was the param)
I found a solution that uses the routes.findAndGetUrls(props.route, props.params)
function, using this internal function to calculate the correct href, and then comparing the value with withRouter
's router.asPath
.
It can tell the difference between
route="about" params={{ slug: "hello", name: "william" }}
and
route="about" params={{ slug: "hello", name: "john" }}
my solution: https://github.com/fridays/next-routes/issues/208
Hi guys 😉
This example with my solution to highlighting an active page of navigation with
useRouter() from 'next/router'
routes.js
const routes = module.exports = require('next-routes')()`
routes
.add("homepage", "/", "index")
.add("blog", "/blog")
.add("bio", "/bio")
Nav.js
import cn from "classnames"
import { Link } from "routes"
import { useRouter } from 'next/router'
const links = {
pages: [
{ href: '/blog', label: 'my articles' },
{ href: '/bio', label: 'bio' }
].map(link => {
link.key = `nav-link-${link.label}`
return link
})
};
const Nav = () => {
<nav>
<ul className="links__list">
{links.pages.map(({ key, href, label }) => (
<li key={key} className={cn("links__item", useRouter().pathname === href && "active")}>
<Link route={href}>
<a>
{label}
</a>
</Link>
</li>
))}
</ul>
<style jsx>
.links__item.active {
border-bottom: 1px solid red;
}
</style>
</nav>
}
export default Nav
✌️