'Declaring React Routes in a separate file and Importing

I am new to React. I have been trying to declare routes in a file and then use it in another file.

Here is my routes.js

import React from 'react';

import { Route } from 'react-router-dom';
import App from './components/App';
import Template1 from './components/template1';
import Template2 from './components/template2';
import Template3 from './components/template3';

const routes = (
  <Route exact path="/" component={App}>
    <Route exact path="/sessionstate1" component={Template1} />
    <Route exact path="/sessionstate2" component={Template2} />
    <Route exact path="/sessionstate3" component={Template3} />
  </Route>
)

export default routes

and index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import './styles/css/index.css';
import routes from './routes.js';

ReactDOM.render(
  <Router history={browserHistory} routes={routes} />,
  document.getElementById('root')
);

I am not getting any errors or warning but the page is not loading. Please tell me what I am missing

Thanks



Solution 1:[1]

well i had the same issue a few days ago, and the solution for me was this...

This one of the routes files:

import React from 'react';
import { Route } from 'react-router-dom';
import { ComponentY } from '../components/functionalitys';

export default [
  <Route path="/appointment" component={ComponentY} exact key="create" />,
];

This another route file:

import React from 'react';
import { Route } from 'react-router-dom';
import { LoginPage, Register } from '../components/user';

export default [
  <Route path="/register" component={Register} exact key="create" />,
  <Route path="/login" component={LoginPage} exact strict key="login" />
];

And this is how I imported in the main app.js:

import routesFromFile1 from './the/route';
import routesFromFile2 from './the/other/route';

class App extends Component{
  render(){
    return(
       <div className="wrapper">
           <section className="content container-fluid">
              <Switch>  
                <Route exact path="/" component={Home} strict={true} exact={true}/>
                <Route path="/500" component={InternalServer} />
                {routesFromFile1}
                {routesFromFile2}
              </Switch>
            </section>
          </div>
        )
    }
}

I hope this help Someone! Cheers!!

Solution 2:[2]

You don't need to wrap your Routes inside a div. Try something like this:

routes.js

import React from 'react';
import { Router, Route } from 'react-router';
import { Template1, Template2, Template3 } from './templates';

const createRoutes = () => (
    <Router>
      <Route exact path="/sessionstate1" component={Template1}/>
      <Route exact path="/sessionstate2" component={Template2}/>
      <Route exact path="/sessionstate3" component={Template3}/>
    </Router>
);

export default createRoutes;

index.js

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

const routes = createRoutes();

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

Solution 3:[3]

index.js:

import LoginRoutes from './login/routes'

let routeConfig = [];
routeConfig = routeConfig.concat(LoginRoutes(store));

<Router routes={routeConfig}/>

routes.js:

export default (store) => {

    return [
        {path: '/login', component: Login},
        {path: '/signup', component: SignUp},
    ]
}

This way you can add routes from different files and spread your route definitions to different folders that serve the contextual purpose of the route.

The store variable is there in case you want to use redux and want to have an onEnter event on the route. Example:

export default () => {

    const sessionEnter = (location) => {
        let {appId} = location.params;

        store.dispatch(loadApp(appId));

    return [
        {path: '/apps/:appId', component: App, onEnter: sessionEnter},
    ]
}

I find onEnter events a good alternative to componentDidMount, data-fetching-wise. Invoking a data fetch on route level makes more sense to me as I see the component as part of the presentation level.

Solution 4:[4]

I think the problem is with wrapping the Route inside a div. Try wrapping them inside a Route like following. Try this fiddle and change the routes wrapper to div.

const routes=(
      <Route >
        <Route exact path="/sessionstate1" component={Template1}/>
        <Route exact path="/sessionstate2" component={Template2}/>
        <Route exact path="/sessionstate3" component={Template3}/>
      </Route >
)
export default routes;

And import it into index.js

import routes from './routes.js';

ReactDOM.render(
    <Router history={browserHistory} routes={routes} />,
    document.getElementById('root')
);

Solution 5:[5]

I know I'm little late but here my working here a working demo

my dependencies are

"react": "16.2.0",
"react-dom": "16.2.0",
"react-router-dom": "4.2.2",
"react-scripts": "1.1.0"

create nav.js file as this this file is responsible for storing all the links for navbar

import React, { Component } from "react";
import { Link } from "react-router-dom";

class Navi extends Component {
  render = () => (
    <div>
      <Link to="/">Go to Home</Link> <br />
      <Link to="/about">Go to About</Link> <br />
      <Link to="/any-route">404 page</Link>
    </div>
  );
}

export default Navi;

Then the routes.js file here you will define all your routes, and your pages where the routes should navigates to

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
// your components
const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const MissingPage = () => <h1>404</h1>;

const routes = (
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/about" component={About} />
    <Route component={MissingPage} />
  </Switch>
);

export default routes;

finally here is the code for index.js

import React, { Component } from "react";
import ReactDOM from "react-dom";

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

import Navi from "./nav";
import routes from "./routes";

// initialize rotues and navi links
const initRoutes = () => (
  <Router>
    <div>
      <Navi />
      {routes}
    </div>
  </Router>
);

const initializedRoutes = initRoutes();
ReactDOM.render(
  initializedRoutes, 
  document.getElementById("root")
);

Solution 6:[6]

With Typescript

Sepate the file for routes as routes.ts

export const routes = [
    { path: '/', component: Home },
    { path: '/auth-callback', component: authCallback },
    { path: '/fetch-data/:startDateIndex?', component: FetchData }
];

In the App.tsx

export function App() {
    const routeComponents = routes.map(({ path, component }, key) => <Route exact path={path} component={component} key={key} />);
    return (
        <Layout>
            {routeComponents}
        </Layout>
    );
}

Layout.tsx

export default (props: { children?: React.ReactNode }) => (
    <React.Fragment>
        <div>
            <NavMenu />
            <TopAppBarFixedAdjust>
                {props.children}
            </TopAppBarFixedAdjust>
        </div>
    </React.Fragment>
);

Solution 7:[7]

Try it like this way

import React from "react";
import {HashRouter as Router, Route} from 'react-router-dom';
import NoteContainer from "./component/note/index.jsx";
import Header from "./component/common/header.jsx";

const App = (props) => {
    return (
        <div className="container">
            <Header/> {props.children}
        </div>
    );
};

var x = () => {
    return (
        <h1>Hello world!</h1>
    );
};
module.exports = () => {
    return (
        <Router>
            <App>
                <Route path="/" component={NoteContainer}/>
                <Route path="/inbox" component={x}/>
            </App>
        </Router>
    );
};

Solution 8:[8]

I did it with very simple way. Follow the two steps below.

In App.js

import "bootstrap/dist/css/bootstrap.min.css";
import Header from "./component/common/header";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";

import routes from "./routes";

function App() {
  return (
    <Router>
      <section className="container">
        <Header />
        {routes}
      </section>
    </Router>
  );
}

export default App;

in routes.js

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Overview from "./component/overview/overview";
import UsersList from "./component/userslist/UsersList";
import FavUserList from "./component/userslist/FavUserList";

const routes = (
  <Switch>
    <Route exact path="/" component={Overview} />
    <Route path="/adduser" component={UsersList} />
    <Route path="/favuser" component={FavUserList} />
  </Switch>
);

export default routes;

Note: Make sure you import like this

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

In < Header /> component you have to declare navigation link.

Solution 9:[9]

Also new to react and was running into the same issue. Here is what I tried (obviously different code and structure, but what we're looking for should be the same functionality)

index.js

import React from "react";
import ReactDOM from "react-dom";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';

import routes from "./routes";

const allRoutes = routes;

ReactDOM.render(
  allRoutes,
  document.getElementById("app")
)

and the routes.js file.

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

import App from "./pages/App";
import Detail from "./pages/Detail";
import List from "./pages/List";

const routes =  (
  <BrowserRouter>
    <div>
        <Route exact path="/" component={ App } />
        <Route path="/" component={ List } />
        <Route path="/detail/:repo" component={ Detail } />
    </div>
  </BrowserRouter>
);

export default routes;

Let me know if that works for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marlon Alejandro Espinosa Cast
Solution 2 Edvinas daugirdas
Solution 3
Solution 4
Solution 5 NuOne
Solution 6 San Jaisy
Solution 7 error404
Solution 8
Solution 9 mcshakes