How to declare React Router routes in a separate file and import them?

Sometimes, we want to declare React Router routes in a separate file and import them.

In this article, we’ll look at how to declare React Router routes in a separate file and import them.

How to declare React Router routes in a separate file and import them?

To declare React Router routes in a separate file and import them, we can create a function that returns the Router components with the Routes inside it.

For instance, we write

import React from "react";
import { Router, Route } from "react-router";
import { Foo, Bar, Baz } from "./templates";

const createRoutes = () => (
  <Router>
    <Route exact path="/foo" component={Foo} />
    <Route exact path="/bar" component={Bar} />
    <Route exact path="/baz" component={Baz} />
  </Router>
);

export default createRoutes;

to create the createRoutes function that returns the Router with the Routes and export it.

Then we use it by writing

import ReactDOM from "react-dom";
import createRoutes from "./routes";

const routes = createRoutes();

ReactDOM.render(routes, document.getElementById("root"));

to call createRoutes and use the returned routes in render.

Conclusion

To declare React Router routes in a separate file and import them, we can create a function that returns the Router components with the Routes inside it.