Home > Mobile >  React is not rendering when i use react-router
React is not rendering when i use react-router

Time:02-15

I'm trying to set-up routers with react and webpack, I have added historyApiFallback: true, to my webpack config file, and then I'm just trying to use router on my App.js which is rendered correctly without router, but when I add the component <Router> or whatever its related to I get nothing rendered.

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

const Home = () => <div>Home</div>;

const About = () => <div>About</div>;

const App = () => (
<Router>
  <Link to="/">Home</Link>
  <Link to="/about">About</Link>

  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
</Router>
);

export default App;

CodePudding user response:

You should use Switch that, as react-router-dom says:

A Switch looks through its children s and renders the first one that matches the current URL.

So your code becomes:

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

const Home = () => <div>Home</div>;

const About = () => <div>About</div>;

const App = () => (
<Router>
  <Link to="/">Home</Link>
  <Link to="/about">About</Link>
  <Switch>
     <Route exact path="/" component={Home} />
     <Route path="/about" component={About} />
  </Switch>
</Router>
);

export default App;

You could see this example.

CodePudding user response:

react-router-dom@5

If using react-rotuer-dom v5 then I don't see any issue with the code, it should render without issue. You may want to render the routes into the Switch component though so you are matching and rendering a single route at-a-time.

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

const Home = () => <div>Home</div>;

const About = () => <div>About</div>;

const App = () => (
  <Router>
    <Link to="/">Home</Link>
    <Link to="/about">About</Link>

    <Switch>
      <Route path="/about" component={About} />
      <Route path="/" component={Home} />
    </Switch>
  </Router>
);

react-router-dom@6

If using react-router-dom v6 then you need to render the routes into the Routes component and render the routed components on the element prop as the Route component API changed; there's no longer the component and render and children function props. The element prop takes a ReactElement, a.k.a. JSX.

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

const Home = () => <div>Home</div>;

const About = () => <div>About</div>;

const App = () => (
  <Router>
    <Link to="/">Home</Link>
    <Link to="/about">About</Link>

    <Routes>
      <Route path="/about" element={<About />} />
      <Route path="/" element={<Home />} />
    </Routes>
  </Router>
);
  • Related