Tony Starkus
Tony Starkus

Reputation: 576

React - Change component by the router

I start learning about React, and I am working in an application in two parts: when the user is logged and is not.

When the user is not logged, the "/" will show the login page. When is logged, will show the Dashboard page. In Dashboard page, there is a top nav and a sidebar in the left, and in the "center" will show the content of the page. Linke in this image from iMaster:

enter image description here

SO the sidebar will have links, that will update the component that is shown as children of the Dashboard component. I searched about "Nested Routes", but no success.

I'm trying to do in this because I see that if I will show the navs in "all" pages, is better load the navs one time and then update the children os the navs, instead of loading the navs in every page.

Anyone can help?

App.js

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Login from './pages/login';
import Dashboard from './pages/dashboard';

const App = () => (

    <div className="App">
      <BrowserRouter>
        <Switch>
            <Route exact path="/" component={Login} />
            <Route exact path="/dashboard" component={Dashboard} />
        </Switch>
    </BrowserRouter>
    </div>

);

export default App;

Dashboard

import React, { Component } from 'react';
//BOOTSTRAP
import 'bootstrap/dist/css/bootstrap.min.css';
import { Col, Container, Row } from 'react-bootstrap';
//BOOTSTRAP

import './styles.css';
import TopSideNavBar from '../../components/TopSideNavBar';


export default class Dashboard extends Component {

    render() {

        return(

            <>

            <div className="body">

                <TopSideNavBar />

                <Container fluid className="content">
                 <Switch>
         <Route path={`${match.path}/component1`} render={Component1}/>
         <Route path={`${match.path}/component2`} render={Component2}/>
                 </switch>
                </Container>

            </div>


            </>

        );

    }
}

Upvotes: 1

Views: 191

Answers (1)

Alex
Alex

Reputation: 3991

Wrap your component with BrowserRouter and correct access to match.path

export default class Dashboard extends Component {
  render() {
    return (
      <BrowserRouter>
       <>

            <div className="body">

            <TopSideNavBar />
            <Switch>
            <Route path={`${this.props.match.path}/component1`} component={Component1} />
            <Route path={`${this.props.match.path}/component2`} component={Component2} />
           </Switch>
           </div>


       </>
      </BrowserRouter>
    );
  }
}

Upvotes: 1

Related Questions