Routing inside subcomponents not working while using 'exact' : ReactJs

Viewed 117

I have created one simple project with 3 main components/pages.

  1. Home page (path: "/") with is login page. once we click on login button, will create a dynamic URL "admin/random_num LogIn.js
import { Link, Route } from "react-router-dom";
import Dashboard from "../Admin/Dashboard";

export default function Login(props) {
  return (
    <div>
      <h1>Login form</h1>
      <Link to={`/admin/${Math.random()}`}>Login Button</Link>
      <Route path="/admin/:aid" component={Dashboard} />
    </div>
  );
}

2nd component/page is admin(path: "/admin/randum_num" , eg: "/admin/132"), which should be displayed when clicked on login button on login page. Admin.js


export default function Dashboard(props) {
  return (
    <div>
      <h1>Admin Dashboard</h1>
    </div>
  )
}

3rd component is 404page, which will simply display when no route is matched. Error404.js


export default function Error404() {
  return (
    <div>
      <h1>404</h1>
    </div>
  )
}

last not the least, in App.js i am setting up routing. App.js

import React from 'react'
import './App.css';
import Error404 from './pages/Error404';
import Login from './pages/StartingScreen/Login';

function App() {
  return (
    <BrowserRouter>
    <div className="App">
      <Switch>
        <Route exact path="/" component={Login} />
        <Route  component={Error404} />
      </Switch>
    </div>
    </BrowserRouter>
  );
}

export default App;

Note: i am able to display the admin dashboard page if i remove "exact" parameter in Route statement but after removing "exact" both Login and Dashboard page will be visible which i dont want. I want only one component should be visible at given route.

I am struggling to find an answer regarding this problem since one week, kindly help. If the given detail is incomplete, let me know.

1 Answers

Since you are using exact for your login component, that means your Login component will only render for the root path /.

And your Dashboard component is inside your Login component, that means you also need to add "/admin/:aid" to your login route.

You need to change this

<Route exact path="/" component={Login} />

to

<Route exact path={["/", "/admin/:aid"]} component={Login} />

Update: To hide login button, you can use another Switch in your Login component

export default function Login(props) {
  return (
    <div>

      <Switch>
        <Route exact path="/">
          <h1>Login form</h1>
          <Link to={`/admin/${Math.random()}`}>Login Button</Link>
        </Route>
        <Route exact path="/admin/:aid" component={Dashboard} />
      </Switch>

    </div>
  );
}
Related