• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

159
Vistas
Nesting a react router inside another component while preserving a sidebar

As an exercise, I'm making a react app (still learning React) that implements a login system with firebase. Of course, to implement such a feature, react router is necessary and I have successfully implemented it. However, once the user logs in he should be able to see a sidebar alongside other content that is changed dynamically. I now need to again use react router to change those pages when a user clicks on a specific item in the sidebar without having to render the sidebar with each component. I have read the docs for nesting routers but just cant get it to work. Any help is greatly appreciated.

Here's the code:

App.js:

import "./App.css";
import LoginForm from "./components/LoginForm";
import { AuthProvider } from "./contexts/AuthContext";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Dashboard from "./components/Dashboard";
import PrivateRoute from "./components/PrivateRoute";



function App() {
  return (
    <div className="App">
      <Router>
        <AuthProvider>
          <Switch>
            <PrivateRoute exact path="/" component={Dashboard} />
            <Route path="/login" component={LoginForm} />
          </Switch>
        </AuthProvider>
      </Router>
    </div>
  );
}

export default App;

Dashboard.js:

import React from "react";
import { useAuth } from "../contexts/AuthContext";
import { useHistory } from "react-router";
import Sidebar from "./Sidebar/Sidebar";
import { useRouteMatch } from "react-router";

const Dashboard = () => {
  const { currentUser, logout } = useAuth();
  const history = useHistory();
  let { path, url } = useRouteMatch();

  const handleLogout = async () => {
    try {
      await logout();
      history.push("/login");
    } catch (error) {
      console.log(error);
    }
  };
  if (!currentUser) return null;
  return (
    <div>
      <Sidebar logout={handleLogout} />
    </div>
  );
};

export default Dashboard;

PS. I'm quite new to react and any tip/critique is welcome

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can always conditionally render the sidebar.

function Sidebar() {
  const { currentUser } = useAuth()
  if (!currentUser) return null
  // ...
}

Within your App component, just render the Sidebar component outside of the Switch:

function App() {
  return (
    <div className="App">
      <Router>
        <AuthProvider>

          <Sidebar />

          <Routes />

        </AuthProvider>
      </Router>
    </div>
  );
}

function Routes() {
  const { currentUser } = useAuth()
  return (
    <Switch>
      {currentUser && <PrivateRoutes />}
      <PublicRoutes />
    </Switch>
  )
}

Basically all you need to do is render the sidebar on all routes. If you need to render custom Sidebar content based off of routes, you can add another Switch within Sidebar. You can add as many Switch components as you want as long as they are within your Router.

almost 3 years ago · Juan Pablo Isaza Denunciar

0

Even though i understand what your trying to do, i don't think you should mind put the sidebar inside the component.

React is powerfull enough to cache a lots of stuffs and disable unnecessary renders. I think the path you should go its figure out how to use wisely useCallback useMemo, memo and make all the tricks to prevent re-renders inside the sidebar components. This way you can reuse the sidebarcomponent, or any component, without to think about location.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda