Home > Blockchain >  React-router is not displaying anything in the browser
React-router is not displaying anything in the browser

Time:12-21

I am trying to build a simple meetup application using React.The folder structure is as below: enter image description here

Inside AllMeetups.js:

function AllMeetupspage(){
return <div>AllMeetups</div>
}

export default AllMeetupspage;

Inside Favourites.js:

function Favouritespage(){
    return <div>favourites</div>
    }
    
export default Favouritespage;

Inside Newmeetup.js,

function NewmeetupPage(){
    return <div>Newmeetup</div>
    }
    
export default NewmeetupPage;

Inside App.js,

import { Route } from 'react-router-dom';
import AllMeetupspage from './pages/AllMeetups';

import NewmeetupPage from './pages/Newmeetup';

function App() {
  return (
    
    <div>
      <Route path='/'>
        <AllMeetupspage />
      </Route>
      <Route path='/new-meetup'>
        <NewmeetupPage />
      </Route>    
    </div>
  );
}

export default App;

Inside index.js,

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from "react-router-dom";

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

I want to see the Allmeetups page content when I load browser.But when I load the browser,it displays nothing.I am new to react and javascript.Could anyone please let me know where I go wrong?

CodePudding user response:

If you're using react-router @v6, you need to replace component with element

<Route path="/" element={<AllMeetupspage />} />
...
...

CodePudding user response:

you have to wrap your routes with the BrowserRouter ( in the below image used as Router) from the react-router-dom for the routing to work. I think this is the issue in your code, sorry if am wrong.

Eg:

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

const App = () => {
return (
    <>
        <Router>
            <Switch>
                <Route path="/" component={HomePage} />
            </Switch>
        </Router>
    </>
);
};

 export default App;

CodePudding user response:

If you are using react-router version@5 or lower you need to do

<Route exact path="/new-meetup" />

because both routes start with the "/" and would always fall back to the first as you don't specify that you want the complete URL match. The exact parameter basically is some kind of regex that says should match the complete url. From the old docs: https://v5.reactrouter.com/web/api/Route/exact-bool With the version@6 its not necessary anymore as react-router by default will always look for the exact path.

  • Related