Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router 4. Get active route

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!

like image 486
Musheg Davtyan Avatar asked May 13 '26 16:05

Musheg Davtyan


2 Answers

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);
like image 130
Dane Avatar answered May 16 '26 05:05

Dane


You can wrap your Main component with withRouter HOC in-order to get the location props from the context.

like image 27
felixmosh Avatar answered May 16 '26 06:05

felixmosh