Search code examples
reactjsreact-routerreact-component

React not rendering Route Components


I am building a consumer facing app with a admin dashboard. I want to keep the routing separate for them and so trying to delegate :-

App.js

import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

//styles
import './style/bootstrap/bootstrap.scss';

//apps
import Mainapp from './mainapp/Mainapp';
import Admin from './admin/Admin';

const MainappContainer = () => (
  <Mainapp />
);

const AdminContainer = () => (
  <Admin />
);

class App extends Component{
  render(){
    return (
      <Router>
        <Switch>
            <Route path="/admin" component={AdminContainer}/>
            <Route path="/" component={MainappContainer}/>
        </Switch>
      </Router>
    )
  }
}

export default App;

Admin.js

import React, {Component} from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';


//styles
import './admin-style.scss';

//layout
import ControlPanel from './component/layout/ControlPanel';
import Navbar from './component/layout/Navbar';

//pages
import Quote from './component/pages/quote/Quote';

class Admin extends Component{
    render(){
      return (
        <div className="adminWrapper">
          <ControlPanel />
          <section className="viewPanel">
            <Navbar />
            <Router>
              <Route path="/quote" component={Quote}/>
            </Router>
          </section>
        </div>
      )
    }
  }

  export default Admin;

However when I hit the URL

http://localhost:3000/admin/quote

it doesn't seem to load the quote component

Quote.js

import React, { Component } from 'react';

class Quote extends Component {
    render() {
        return (
            <div className="float-right pr-3">
                <h3>
                    Quote Page
                </h3>
            </div>
        )
    }
}

export default Quote;

Solution

  • Follow the Nested Routing Example

    The main changes you need to do are:
    1. Remove the <Router></Router> from Admin component and
    2. Prepend match.path to "/quotes", like it is done in Topics component in the example. In the example, Topics is a function component so it is receiving match as function parameter. As your Admin component is class component, you can access it as this.props.match in render method.

    <Route path={`${this.props.match.path}/quote`} component={Quote}/>