`react-router-dom` is not rendering anything

Viewed 746

I started a basic react project with npx create-react-app web and running with npm start. I am using react-router-dom to handle navigation and the project is as follows:


index.js

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>, 
    document.getElementById('root')
)


App.js:

function Home() {
  return (
    <div>
      <h2>Home</h2>
      <div>
        I am at home, this should render as expected
      </div>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}

class App extends Component {

    render(){
        return(
            <main>
                <Routes>
                    <Route path='/' element={Home} />                
                    <Route path='/About' element={About} />                
                </Routes>
            </main>
        )
    }


}

export default App;

When I go to localhost:3000, I am seeing nothing but a blank page, what am I missing here?

2 Answers

correct your syntax by using:

class App extends Component {

    render(){
        return(
            <Router>
                <Routes>
                    <Route path='/' element={<Home/>} />                
                    <Route path='/About' element={<About/>} />                
                </Routes>
            </Router>
        )
    }


}

export default App;

Also import router like this if you have'nt,

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

I hope it will resolve your issue.

It's a basic syntax issue, I can't delete the question because it's already been upvoted. I see there's some general confusion so the old way:

<Route exact path="/" render={() => (<Foo/>)}/>

or

<Route path="/" element={Foo}/>

no longer works. Below is the complete working example:

Here it is with proper syntax:

function Home() {
  return (
    <div>
      <h2>Home</h2>
      <div>
        I am at home, this should render as expected
      </div>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}

class App extends Component {

    render(){
        return(
            <BrowserRouter>
            <Routes>
                <Route exact path='/' element={<Home/>}/>
                <Route exact path='/about' element={<About/>}/>
                <Route exact path='/dashboard' element={<Dashboard/>}/>
            </Routes>
            </BrowserRouter>
        )
    }


}

Related