Tag Archives: React series

React Error You should not use or withRouter() outside a

App.js in the code

import React, {Component , Fragment} from 'react';
import {withRouter , Route , Switch , Redirect} from 'react-router-dom';
import './App.css';
import 'antd/dist/antd.css'
import Home from './component/Home';
import List from './component/List';
@withRouter
class App extends Component {
    render() {
        return (
            <Fragment>
                <Switch>
                    <Route path='/homePage' component={Home}></Route>
                    <Route path='/listPage' component={List}></Route>
                    <Redirect to={`/homePage`}/>
                </Switch>
            </Fragment>

        );
    }
}
export default App;

Running project error:

←→1 of 2 errors on the page
You should not use <Route> or withRouter() outside a <Router>
▶ 26 stack frames were collapsed.
./src/index.js
C:/Users/abcd/WebstormProjects/ant-table-demo/src/index.js:7
   4 | import App from './App';
   5 | import registerServiceWorker from './registerServiceWorker';
   6 | 
>  7 | ReactDOM.render(<App />, document.getElementById('root'));
   8 | registerServiceWorker();
   9 | 
  10 | 
View compiled
▶ 6 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

The solution
Package the App components via Route, as follows:

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

const Root = () => {
    return (
        <BrowserRouter basename='/'>
            <Route path={`/`} component={App}></Route>
        </BrowserRouter>
    )

}

ReactDOM.render(<Root/>, document.getElementById('root'));

Then it will run correctly