Angad
Angad

Reputation: 1174

React-Router nested routes loading blank page instead of loading inside parent component

I am new to React and trying to create a layout with nested routes. Here's my scenario

The login page and dashboard page are loading properly when the URL is accessed in the browser but for /dashboard/profile, the browser goes to a blank page instead of loading it inside the dashboard component.

Index.js

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>, 
    document.getElementById('root'));

App.js

class App extends Component {
  render() {
    return (
      <div>
        {/* <Switch> */}
          <Route exact path='/' component={SignIn}/>
          <Route exact path='/dashboard' component={Dashboard}/>
        {/* </Switch> */}
      </div>
    );
  }
}

export default App;

Dashboard.js

class Dashboard extends React.Component {

  render() {
    const { classes } = this.props;

return (
  <React.Fragment>
    <CssBaseline />
    <div className={classes.root}>
      <Header classes={classes} open={this.state.open} click={this.handleDrawerOpen} />
      <Sidebar classes={classes} open={this.state.open} click={this.handleDrawerClose} />
      <main className={classes.content}>
        <div className={classes.appBarSpacer} />           

        *********I expect profile component to load here 
but when I access the URL /dashboard/profile I get a new blank page*********

        Route path="/dashboard/profile" exact component={Profile} />



      </main>
    </div>
  </React.Fragment>
);
  }
}

Upvotes: 3

Views: 2355

Answers (1)

Murli Prajapati
Murli Prajapati

Reputation: 9713

You need to remove the exact prop from the Dashboard route (present in Switch) while doing the child routing.

This is the minimal implementation of your use case:

import React, { Component } from "react";
import "./styles.css";

import {
  NavLink,
  Redirect,
  Route,
  BrowserRouter as Router,
  Switch
} from "react-router-dom";

const App = () => (
  <Router>
    <div className="App">
      <ul>
        <li>
          <NavLink to="/login">Login</NavLink>
        </li>
        <li>
          <NavLink to="/dashboard">Dashboard</NavLink>
        </li>
      </ul>

      <Switch>
        <Route exact path="/login" component={Login} />
        <Route path="/dashboard" component={Dashboard} />
      </Switch>
    </div>
  </Router>
);

const Login = () => <span>Login Page</span>;

const Dashboard = () => {
  return (
    <div>
      <div>Dashboard Page</div>
      <NavLink to="/dashboard/profile">Go to profile</NavLink>
      <div>
        <Route exact path="/dashboard/profile" component={Profile} />
      </div>
    </div>
  );
};

const Profile = () => {
  return <span>Profile Page</span>;
};

export default App;  

You can find the working example here:https://codesandbox.io/s/z3py3672v3

Upvotes: 5

Related Questions