How to Fix the “A ‘Router’ may have only one child element” Error with React Router?

Sometimes, we may encounter the “A ‘Router’ may have only one child element” Error with React Router.

In this article, we’ll look at how to fix the “A ‘Router’ may have only one child element” Error with React Router.

Fix the “A ‘Router’ may have only one child element” Error with React Router

To fix the “A ‘Router’ may have only one child element” when developing React apps with React Router, we should make sure we have only one child component inside the Router component.

For instance, we write:

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

const Foo = () => {
  return <p>foo</p>;
};

const Bar = () => {
  return <p>bar</p>;
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <NavLink to="/foo">foo</NavLink>
          </li>
          <li>
            <NavLink to="/bar">bar</NavLink>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

to wrap everything inside Router in a single div.

Conclusion

To fix the “A ‘Router’ may have only one child element” when developing React apps with React Router, we should make sure we have only one child component inside the Router component.