Home > Enterprise >  react-router-dom v6 rendering new page over current page
react-router-dom v6 rendering new page over current page

Time:04-28

the problem is the following. in the app.js is spelled out Routes and the home component. the home contains a navbar that navigates the site, only if you go to any page, it is drawn on top of the home. And if you switch to the home itself, it will be duplicated. Articles on the internet did not help, as did the addition of exact in route path.

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

            <Routes>
                <Route path="/home/" element={<Home/>}/>
                <Route path="/settings/" element={<Settings/>}/>
                <Route path="/login/" element={<Login/>}/>
                <Route path="/register/" element={<Register/>}/>
            </Routes>

            <Home/>

        </div>
    )

home

export default class Home extends Component {
    render() {
        return (
            <div>
                <NavBar/>
                <ChatMenu/>
            </div>
        );
    }
}

an example of how it is written in the navbar

    export const NavBar = () => {
            return (<div className="navbar-cm">
        
                    <div className="nav_element">
                        <Link to="/home">
                            <img src={homeIMG} className="nav_element"/>
                        </Link>
                    </div>
and a few more similar ones
    </div>);
    };

CodePudding user response:

Issue

You are rendering the Home component again once outside the routes, this is why it's rendered with all routes including twice when on the "/home" path that renders Home.

function App() {
  return (
    <div className="messenger">
      <Routes>
        <Route path="/home/" element={<Home />} />
        <Route path="/settings/" element={<Settings />} />
        <Route path="/login/" element={<Login />} />
        <Route path="/register/" element={<Register />} />
      </Routes>

      <Home /> // <-- always rendered below routed content
    </div>
  )
}

Solution

Remove the Home component that is out on its own outside the routes.

function App() {
  return (
    <div className="messenger">
      <Routes>
        <Route path="/home/" element={<Home />} /> // <-- now only Home component rendered
        <Route path="/settings/" element={<Settings />} />
        <Route path="/login/" element={<Login />} />
        <Route path="/register/" element={<Register />} />
      </Routes>
    </div>
  )
}

CodePudding user response:

Remove <Home /> from the router:

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

            <Routes>
                <Route path="/home/" element={<Home/>}/>
                <Route path="/settings/" element={<Settings/>}/>
                <Route path="/login/" element={<Login/>}/>
                <Route path="/register/" element={<Register/>}/>
            </Routes>
        </div>
    )
  • Related