score:376
in the 5.1 release of react-router there is a hook called uselocation, which returns the current location object. this might useful any time you need to know the current url.
import { uselocation } from 'react-router-dom'
function headerview() {
const location = uselocation();
console.log(location.pathname);
return <span>path : {location.pathname}</span>
}
score:1
add
import {withrouter} from 'react-router-dom';
then change your component export
export default withrouter(componentname)
then you can access the route directly within the component itself (without touching anything else in your project) using:
window.location.pathname
tested march 2020 with: "version": "5.1.2"
score:11
i think the author's of react router (v4) just added that withrouter hoc to appease certain users. however, i believe the better approach is to just use render prop and make a simple propsroute component that passes those props. this is easier to test as you it doesn't "connect" the component like withrouter does. have a bunch of nested components wrapped in withrouter and it's not going to be fun. another benefit is you can also use this pass through whatever props you want to the route. here's the simple example using render prop. (pretty much the exact example from their website https://reacttraining.com/react-router/web/api/route/render-func) (src/components/routes/props-route)
import react from 'react';
import { route } from 'react-router';
export const propsroute = ({ component: component, ...props }) => (
<route
{ ...props }
render={ renderprops => (<component { ...renderprops } { ...props } />) }
/>
);
export default propsroute;
usage: (notice to get the route params (match.params) you can just use this component and those will be passed for you)
import react from 'react';
import propsroute from 'src/components/routes/props-route';
export const somecomponent = props => (<propsroute component={ profile } />);
also notice that you could pass whatever extra props you want this way too
<propsroute isfetching={ isfetchingprofile } title="user profile" component={ profile } />
score:28
has con posidielov said, the current route is present in this.props.location.pathname
.
but if you want to match a more specific field like a key (or a name), you may use matchpath to find the original route reference.
import { matchpath } from `react-router`
const routes = [{
key: 'page1'
exact: true,
path: '/page1/:someparam/',
component: page1,
},
{
exact: true,
key: 'page2',
path: '/page2',
component: page2,
},
]
const currentroute = routes.find(
route => matchpath(this.props.location.pathname, route)
)
console.log(`my current route key is : ${currentroute.key}`)
score:34
here is a solution using history
read more
import { createbrowserhistory } from "history";
const history = createbrowserhistory()
inside router
<router>
{history.location.pathname}
</router>
score:73
there's a hook called uselocation in react-router v5, no need for hoc or other stuff, it's very succinctly and convenient.
import { uselocation } from 'react-router-dom';
const examplecomponent: react.fc = () => {
const location = uselocation();
return (
<router basename='/app'>
<main>
<appbar handlemenuicon={this.handlemenuicon} title={location.pathname} />
</main>
</router>
);
}
score:88
if you are using react's templates, where the end of your react file looks like this: export default somecomponent
you need to use the higher-order component (often referred to as an "hoc"), withrouter
.
first, you'll need to import withrouter
like so:
import {withrouter} from 'react-router-dom';
next, you'll want to use withrouter
. you can do this by change your component's export. it's likely you want to change from export default componentname
to export default withrouter(componentname)
.
then you can get the route (and other information) from props. specifically, location
, match
, and history
. the code to spit out the pathname would be:
console.log(this.props.location.pathname);
a good writeup with additional information is available here: https://reacttraining.com/react-router/core/guides/philosophy
score:246
in react router 4 the current route is in -
this.props.location.pathname
.
just get this.props
and verify.
if you still do not see location.pathname
then you should use the decorator withrouter
.
this might look something like this:
import {withrouter} from 'react-router-dom';
const somecomponent = withrouter(props => <mycomponent {...props}/>);
class mycomponent extends react.component {
somemethod () {
const {pathname} = this.props.location;
}
}
Source: stackoverflow.com
Related Query
- React router v6 how to get current route in class component
- React Router v4 - How to get current route?
- react router - get current route
- How can I match if the current route matches a pattern in React Router Dom v6?
- How to get the current pathname correctly in React Router v6?
- How to get React Router to recognize a new route on a dynamic path
- How to get the current route from react without props
- How to get the last part of the current URL with react router v6?
- How can I get the correct current path in React using react router 4.2.2's withRouter?
- how to get route param values of child component from parent component in app using React Router
- React router get current route outside component
- React router how to get current path and look for its updates
- How to get the React router path on route change
- How to set the DefaultRoute to another Route in React Router
- How to get current route in react-router 2.0.0-rc5
- React Router - how to constrain params in route matching?
- react router get full current path name
- How to get params in component in react router dom v4?
- How to pass the match when using render in Route component from react router (v4)
- Conditionally set active class on menu using react router current route
- How would I test for a react router route param in react-testing-library?
- React Router V4 Get Current Path
- Get the current active screen route of the tab navigator in react navigation
- How to fix React Router component not updating as route changes
- How does React Router get into the React context?
- How can i access the current hash location on react router 2?
- React Router v4 get current location
- React router nested routes - How to redirect when no route is matching
- how to get current react component name inside custom react hook?
- how to pass props to the route when using react router <Link>
More Query from same tag
- How to get more API records when the response size is limited
- How to nest children components into parent and export them?
- Is there any way to use Modal component inside app class in react?
- Unify input value with React useState
- How to access more than one element of Dom in react using React.createRef()
- Reactjs console errors: 'Components object is deprectated' & 'ReferenceError: require is not defined'
- Highcharts animation occurs every render
- Can I make multiple useMutation in a components
- React.js - Redux Hooks Invalid Hook Call
- reactjs how to input multiple file from form
- forEach() does not update the values inside a database call
- Using redux to take a time on a stopwatch and put it into a database
- Semantic-UI React: How to theme using less variables in a create-react-app project
- Component for TransitionGroup
- if else statement not working in react component
- Javascript: Add 30 days to date?
- React - Using a custom hook to call another hook - a clean approach?
- antd table actions and onrow function
- How to style the react-stripe-checkout form?
- I need to rerender functional component
- What's the name (type) of redux function 'connect(mapStateToProps)(ConnectedList)'
- Modify an HTML element from one component in another component in React.js
- Add button with onclick event to each row in datatable in react js
- React: Persisting state in tabs
- ERROR in Entry module not found: Error: Can't resolve './src' in
- Best way to convert array in javascript
- How to prevent adding duplicate items to cart using react
- Why is my custom Tailwind CSS utility not applying to React elements?
- npm ERR! Cannot read property 'version' of null
- React component retrieves props just once, goes undefined when refreshed