React Router: Component not getting displayed

Viewed 515

I have just started with React and not able to get the router working. Below is the code for router. If I use the individual components without the router, they are displayed on the screen. But with router I don't get any text on the screen across any of the paths.

Please let me know if I am missing something. Below is the code:

import { Route } from 'react-router-dom';

import AllMeetupsPage from './pages/AllMeetups';

import NewMeetupPage from './pages/NewMeetup';

function App() {
  return (
  <div> 
    <Route path='/' exact>
      <AllMeetupsPage />
    </Route>
    
    <Route path='/new-meetup'>
      <NewMeetupPage />
    </Route>

  </div>);
}

export default App;
2 Answers

A route needs to be a descendent of router component. I'm not sure which version of react-router you're using, but this will be a BrowserRouter and Routes component for react-router v6 and on v4/v5 it'll be a BrowserRouter

Here's some examples:

v6:

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

import AllMeetupsPage from './pages/AllMeetups';

import NewMeetupPage from './pages/NewMeetup';

function App() {
  return (
  <div>
    <BrowserRouter>
      <Routes>
        <Route path="/" exact element={<AllMeetupsPage />}/>
        <Route path="/new-meetup" element={<NewMeetupPage />}/>
      </Routes>
    </BrowserRouter>
  </div>);
}

export default App;

You missed using Switch component

import { Route , Switch } from 'react-router-dom';

function App() {
  return (
  <div> 
  <Switch>
        <Route path='/' exact>
          <AllMeetupsPage />
        </Route>
        
        <Route path='/new-meetup'>
          <NewMeetupPage />
        </Route>
    </Switch>

  </div>);
}

export default App;
Related