Rudy Lai

Detecting an index child route in React Router

2024-06-24

In react-router, how do we detect programmatically that we are on an index path of a child route? This took me a while to figure out, so here it is for all to see:

In React Router, detecting if you are on the index path of a child route can be done by using the useLocation and useMatch hooks. Here’s a step-by-step guide to achieve this:

  1. Install React Router: Ensure you have React Router installed in your project. If not, you can install it using npm or yarn:

    npm install react-router-dom
    
  2. Set Up Routes: Define your routes using react-router-dom. For example:

    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
    import Home from './Home';
    import Parent from './Parent';
    import Child from './Child';
    
    function App() {
      return (
        <Router>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="parent" element={<Parent />}>
              <Route index element={<Child />} />
            </Route>
          </Routes>
        </Router>
      );
    }
    
    export default App;
    
  3. Detect Index Route in Child Component: Use the useLocation and useMatch hooks to check if the current path matches the index path of the child route.

    import { useLocation, useMatch } from 'react-router-dom';
    
    function Child() {
      const location = useLocation();
      const isIndex = useMatch('/parent');
    
      return (
        <div>
          <h1>Child Component</h1>
          {isIndex && location.pathname === '/parent' && (
            <p>This is the index path of the child route</p>
          )}
        </div>
      );
    }
    
    export default Child;
    

In the Child component, we use useLocation to get the current location and useMatch to check if the current route matches the parent route. The condition isIndex && location.pathname === '/parent' ensures that we are on the index path of the child route.

The useMatch is key here. I don't know why the documentation about it is so sparse. It just says (as of July 2024) "returns match data about a route at the given path relative to the current location."

By following these steps, you can programmatically detect if you are on an index path of a child route in React Router.

← Back to articles