Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  78] [ 4]  / answers: 1 / hits: 16198  / 6 Years ago, thu, january 11, 2018, 12:00:00

I have code



router.js



import React from 'react';
import {render} from react-dom;
import history from './history';
import {Router, Route} from 'react-router'

import Main from ./main/component;
import Profile from ./profile/component;
import TextStatus from ./textstatus/component;
import ContactList from ./contactlist/component;

render((
<Router history={history}>
<Main>
<Route
path=/:user_name
component={Profile}
component_id=Profile
/>
<Route
path=/:user_name/status
component={TextStatus}
component_id=TextStatus
/>
<Route
path=/:user_name/contacts
component={ContactList}
component_id=ContactList
/>
</Main>
</Router>

), document.getElementById(main));


history.js



import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();
export default history;


main/component.js //main layout



import React from 'react';
class Main extends React.Component {
render() {
return (this.props.children)
}
}


How can I get the current route (component_id) in Main component?



In react router 1.0.3 I did this: this.props.children.props.route.component_id



Thank you for attention!


More From » reactjs

 Answers
5

Update for React v16.8+ & React Router v5+:


Use useLocation hook.


import { useLocation } from 'react-router-dom';

const Main = ({ children }) => {
const location = useLocation();

console.log(location.pathname); // outputs currently active route
return children;
};

export default Main;

Wrap your components with withRouter and then you can access the current active route using this.props.location.pathname.


Eg:


import React from 'react';
class Main extends React.Component {
render() {
console.log(this.props.location.pathname); // outputs currently active route
return (this.props.children)
}
}
export default withRouter(Main);

[#55483] Monday, January 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;