A router may have only one child element – React Router Dom Error

Total
0
Shares

React router dom throws the error that a router may have only one child element if more than 1 routes are defined without enclosing them in div or switch.

Generally, navigation is used over the whole application. That’s why component like BrowserRouter or Router expects that the top level component like App, should be enclosed in them. They do not expect multiple routes to be listed in them as children.

This code will throw the router error –

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

export default function App() {
    return (
       <BrowserRouter>

           <Route exact={true} path='/route1' render={() => (
               <div>
                  <p>Route 1</p>
               </div>
            )}/>
           <Route exact={true} path='/route2' render={() => (
               <div>
                  <p>Route 2</p>
               </div>
            )}/>
       </BrowserRouter>

    );
}

You can see that we are using 2 Route in BrowserRouter. To, solve this issue, you can either enclose them in Switch or div.

This code will not throw the error and will work fine –

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

export default function App() {
    return (
       <BrowserRouter>
         <Switch>

           <Route exact={true} path='/route2' render={() => (
               <div>
                  <p>Route 1</p>
               </div>
            )}/>
           <Route exact={true} path='/route2' render={() => (
               <div>
                  <p>Route 1</p>
               </div>
            )}/>
         </Switch>
       </BrowserRouter>

    );
}

    Tweet this to help others

Note: The latest version of React-Router-Dom doesn’t have this issue. So, update the package and the error will be gone.