Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with BrowserRouter – navigation doesn't work properly

This is my first reactjs application and I have an issue with the navigation. When I try to navigate via url …/posts or ../home only the main App page is showing up. How can I fix this? Thank you in advance!

I have App main page where user can Login or Register:

import React,{useState, useEffect} from 'react';
import {Register} from './subcomponents/Register';
import {Login} from './subcomponents/Login';

export function App() {
   return (
    <div className="root"> 
      <Login />
      <p>Hi {name}</p>
      <Register/>
    </div>
  );
}

Home page, when the user is logged in to be redirected:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from 'react';
import { Posts } from './Posts';
import {Home} from './Home.jsx';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import {Nav} from './Nav';

export function Home(){
    return(
        <div id="home">
            <BrowserRouter>
                <Nav/>
                <Routes>
                    <Route path='/home' element={<Home/>}/>
                    <Route path="/posts" element={<Posts/>}/>
                </Routes>
            </BrowserRouter>
            <h3>This is the home page</h3>
        </div>
    )
}

Nav component:

import React from 'react';
import {Link} from 'react-router-dom'
import '../css/nav.css';
import Logo from '../images/Logo.png';

export function Nav(){
    return(
        <div id="nav">
            <img src={Logo} className="nav-logo" alt="logo"/>
            <ul>
                <li>
                    <Link to="/home">Home</Link>
                </li>
                <li>
                    <Link to="/posts">Posts</Link>
                </li>
            </ul>
        </div>
    )
}

enter image description here

>Solution :

route components must be in app.jsx/js (root page)

 export function App(){
        return(
             <BrowserRouter>
                <div id="app">  
                   <Routes>
                       <Route path='/home' element={<Home/>}/>
                       <Route path="/posts" element={<Posts/>}/>
                   </Routes>          
               </div>
           </BrowserRouter>
        )
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading