Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Render multiple Route into a main Router in react-router-dom v5

I have multiple components with different paths (routes) and would like to export those to a single Main router component.

For example:

routeComponent1.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function childRoutes() {
  return (
    <div>
      <Route path="/foo" component={foo} />
      <Route path="/bar" component={bar} />
    </div>
  );
}

routeComponent2.js

export default function childRoutes2() {
  return (
    <div>
      <Route path="/foo2" component={foo2} />
      <Route path="/bar2" component={bar2} />
    </div>
  );
}

I would like to use it in

root.js

import routeComponent1 from 'routeComponent1.js';
import routeComponent2 from 'routeComponent2.js';

class Root extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <Router>{routeComponent1}</Router>;
  }
}

It is giving an error – Invariant Violation: <Route> elements are for router configuration only and should not be rendered.

Expecting the

<Router>
  <div>
    <Route path="/foo" component={foo} />
    <Route path="/bar" component={bar} />
  </div>
</Router>

>Solution :

routeComponent1 and routeComponent2 are React components. React components are Capitalized and rendered as JSX.

Example:

import RouteComponent1 from 'routeComponent1.js';
import RouteComponent2 from 'routeComponent2.js';

class Root extends Component {
  render() {
    return (
      <Router>
        <RouteComponent1 />
        <RouteComponent2 />
      </Router>
    );
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading