Home > Enterprise >  React Router: Component not getting displayed
React Router: Component not getting displayed

Time:01-01

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;

CodePudding user response:

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>
          <AllMeetupsPage />
        </Route>

        <Route path='/new-meetup'>
          <NewMeetupPage />
        </Route>
      </Routes>
    </BrowserRouter>
  </div>);
}

export default App;

or v4/v5

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

import AllMeetupsPage from './pages/AllMeetups';

import NewMeetupPage from './pages/NewMeetup';

function App() {
  return (
  <div>
    <Router>
      <Route path='/' exact>
        <AllMeetupsPage />
      </Route>

      <Route path='/new-meetup'>
        <NewMeetupPage />
      </Route>
    </Router>
  </div>);
}

export default App;

CodePudding user response:

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