Home > front end >  navigation is giving me blank page
navigation is giving me blank page

Time:03-28

I used ReactJS a year ago only once just for a small project, however, now I have a problem setting the navigation. The navigation on the old project it's working, I found out there is a new version of react-router-dom, I tried to implement the changes into the code but still, it doesn't work. I don't have a clue why :( any hint is appreciated. Thank you!

Console error:

Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

The above error occurred in the <Route> component:

App.js:

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

export function App() {
  return (
    <div className="App">
      <Nav/>
       <BrowserRouter>
          <Routes>
            <Route path="/" element={<App/>}/>
            <Route path="/posts" element={<Posts/>}/>
          </Routes>
       </BrowserRouter>
    </div>
  );
}

Nav:

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

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

index:

import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './components/App';
import {BrowserRouter, BrowserRouter as Router, Route} from 'react-router-dom';


ReactDOM.render(
  <BrowserRouter>
      <Router>
        <Route path='/' element={<App/>}/>
      </Router>
  </BrowserRouter>
, document.getElementById("root"));

CodePudding user response:

React-Router updated quite a lot, I recommended read the documentation and don't do anything in the index.js file usually to routing in App.js file

import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './components/App';

ReactDOM.render(
  <App />
, document.getElementById("root"));

App.js file

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

export function App() {
  return (
    <div className="App"> 
       <BrowserRouter>
          <Nav/>
          <Routes>
            <Route path="/posts" element={<Posts/>}/>
            <Route path="*" element={<Navigate to="/posts" />} />
          </Routes>
       </BrowserRouter>
    </div>
  );
}
  • Related