DHIS2 React App - transitioning from one component to another using react-router-dom

Hi,

I’m trying to use react-router-dom(6.2.1) to transition from one component to another, but it is breaking the application when I try to build it. The code below is the piece that is stopping the application from building. Thanks

import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import Details from './components/Details';
import EntityTable from './components/EntityTable';

const AppRouter = () => (
    <Router>
        <Switch>
            <Route exact path="/" component={EntityTable} />
            <Route path="/details" component={Details} />
        </Switch>
    </Router >
);
export default AppRouter

Best,
OM

See if this one works, please:

@Orly_MUGWANEZA I don’t think it is required to use Router (BrowserRouter) and Switch at the same time, either. I think you can also remove <Router> </Router> since you are using <Switch></Switch> (or viceversa) and if you remove <Router> then you no longer need to import {BrowserRouter as Router}

Hope this works! (See post below)

@Gassim I have just tried both suggestions and none is working.

Hello @Orly_MUGWANEZA

react-router-dom v6 has a bit different implementation from the one you used (I’m guessing v5 , see here).

The changes affecting your code are the Switch component is replaced with Routes
and the Route prop component is now element. Also as @Gassim suggested, the import should be BrowserRouter as Router.

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Details from './components/Details';
import EntityTable from './components/EntityTable';

const AppRouter = () => (
    <Router>
        <Routes>
            <Route exact path="/" element={<EntityTable/>} />
            <Route path="/details" element={<Details/>} />
        </Routes>
    </Router >
);
export default AppRouter

3 Likes

Yes! :smiley: Thanks for the correction @nnkogift!

Not in React Router v6. So you’d instead be using <Routes><Route /></Routes> and like Gift corrected, we should now use element instead of component. :smiley:

And @nnkogift, also exact has been removed. I just read this:
* <Route exact> is gone. Instead, routes with descendant routes (defined in other components) use a trailing * in their path to indicate they match deeply example: <Route path=“users/*” element={} />

@Orly_MUGWANEZA Please let us know if the code Gift shared worked. Thank you!

1 Like

It worked like magic. Many thanks to you @nnkogift and @Gassim.

1 Like