Home > Mobile >  ReactJS react-router-dom ^5.3.0 not rendering components
ReactJS react-router-dom ^5.3.0 not rendering components

Time:01-29

I was using this code without the BrowserRouter component wrapping the Switch and it worked well. When did some jest testing I have got the following error Invariant failed: Browser history needs a DOM which says that the Link component cannot be used outside a router. Indeed, I was not using the router. When I have added the router, the url is changing but components are not redered properly. Did I make it correct?

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


export const _routes = [
    {
        component: Home,
        path: '/',
        exact: true
    },
    {
        component: Orders,
        path: '/orders',
        exact: false
    },
    {
        component: OrderConfirm,
        path: '/order-confirm',
        exact: false
    }
]

const App = () => <>
    <Navbar />
    <Router>
        <Switch>
            {_routes.map(route => <Route key={route.path} path={route.path} component={route.component} exact={route.exact} />)}
        </Switch>
    </Router>
</>

CodePudding user response:

This should work as expected :

export const _routes = [
    {
        component: 'Home',
        path: '/',
        exact: true
    },
    {
        component: 'Orders',
        path: '/orders',
        exact: false
    },
    {
        component: 'OrderConfirm',
        path: '/order-confirm',
        exact: false
    }
]



const App = () => <>
    <Navbar />
    <Router>
        <Switch>
            {_routes.map(route => <Route key={route.path} path={route.path} component=require(`./components/${route.component}`).default exact={route.exact} />)}
        </Switch>
    </Router>
</>

I assume that your components are inside components package (this./components/${route.component} shoud be path to your component)

  •  Tags:  
  • Related