Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-use navbar component with multiple components

I have a simple question. What is the best way to use a navbar with multiple components using react router? Just let me show the code so you can understand what I'm trying to say.

import React from "react";
import "./App.css";

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

import Auth from "./website/Auth/Auth";
import SocialMedia from "./website/SocialMedia/SocialMedia";
import SingleUser from "./website/SingleUser/SingleUser";
import Search from "./website/Search/Search";
import SinglePhoto from "./website/SinglePhoto/SinglePhoto";

import Navbar from "./components/Navbar/Navbar";

function App() {
  const logIn = JSON.parse(localStorage.getItem("token"));

  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Auth}>
          {logIn ? <Redirect to={`/profile/${logIn.data.id}`} /> : <Auth />}
        </Route>
        <Navbar>
          <Route exact path="/profile/:id" component={SingleUser} />
          <Route exact path="/socialmedia" component={SocialMedia} />
          <Route exact path="socialmedia/search" component={Search} />
          <Route exact path="socialmedia/photo/:id" component={SinglePhoto} />
        </Navbar>
      </Switch>
    </Router>
  );
}

export default App;

So I have to reuse my Navbar component, and I tried to use <Navbar />, then the other routes below, but that wasn't working, and when I put <Navbar> </Navbar> that worked and the other components will appear, but is that the way I reuse my Navbar component?

Thanks for your time !!

like image 246
Diego Davincci Avatar asked Apr 06 '26 22:04

Diego Davincci


1 Answers

import React from "react";
import "./App.css";

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

import Auth from "./website/Auth/Auth";
import SocialMedia from "./website/SocialMedia/SocialMedia";
import SingleUser from "./website/SingleUser/SingleUser";
import Search from "./website/Search/Search";
import SinglePhoto from "./website/SinglePhoto/SinglePhoto";

import Navbar from "./components/Navbar/Navbar";

function App() {
  const logIn = JSON.parse(localStorage.getItem("token"));

  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Auth}>
          {logIn ? <Redirect to={`/profile/${logIn.data.id}`} /> : <Auth />}
        </Route>
        <Route Component={Navbar}>
          <Route exact path="/profile/:id" component={SingleUser} />
          <Route exact path="/socialmedia" component={SocialMedia} />
          <Route exact path="socialmedia/search" component={Search} />
          <Route exact path="socialmedia/photo/:id" component={SinglePhoto} />
        </Route>
      </Switch>
    </Router>
  );
}

export default App;

Try this!

like image 131
Vinicius Katata Avatar answered Apr 09 '26 11:04

Vinicius Katata