Skip to content

Instantly share code, notes, and snippets.

@tjenkinson
Last active April 16, 2020 21:40
Show Gist options
  • Save tjenkinson/b93b95b4ad6de4971ae44fc24087b9d0 to your computer and use it in GitHub Desktop.
Save tjenkinson/b93b95b4ad6de4971ae44fc24087b9d0 to your computer and use it in GitHub Desktop.
Get the base url to a react router route handler.
import React from 'react'
import { Link } from 'react-router'
import getRouteHandlerBaseUrl from 'js/helpers/get-route-handler-base-url'
class Something extends React.Component {
componentWillMount() {
this._baseUrl = getRouteHandlerBaseUrl(this.props)
}
render() {
return (
<div>
<Link to={this._baseUrl+"/something-else"}>Link to [url to this handler]/something-else</Link>
</div>
)
}
}
export default Something
// calculate the base url for a router handler from the props the router provides to it
export default function(props) {
if (!props.route || !props.routes || !props.location) {
throw new Error("Missing props from React router.")
}
var route = props.route
var routeDepth = props.routes.indexOf(route)
return props.location.pathname.split("/").slice(0, routeDepth+1).join("/")
}
@tjenkinson
Copy link
Author

Note this is slightly wrong because paths may contain multiple "/"'s. I have a fixed version but it's changed a bit. If you need it reply here.

@Markkos89
Copy link

this works to deploy my site to netlify for example?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment