Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 203
Vipin Avatar asked Mar 26 '17 08:03

Vipin


People also ask

Where do I import routes in React?

Convert adminRoutes into a React component and ensure the routed components are rendered on the element prop as JSX. React component names use PascalCase. Move the path="/admin/*" to Routes component which will render this component.

Do I need to import React in every file?

You no longer need to import React from "react" . Starting from the release 17 of React, JSX is automatically transformed without using React. createElement . However, other exports like hooks must be imported.

How do I add React routes?

How to Install React Router. To install React Router, all you have to do is run npm install react-router-dom@6 in your project terminal and then wait for the installation to complete. If you are using yarn then use this command: yarn add react-router-dom@6 .

Does React allow nested routes?

Nested Routes are a powerful feature. While most people think React Router only routes a user from page to page, it also allows one to exchange specific fragments of the view based on the current route.


3 Answers

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')
);
like image 118
Edvinas daugirdas Avatar answered Oct 08 '22 20:10

Edvinas daugirdas


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!!

like image 15
Marlon Alejandro Espinosa Cast Avatar answered Oct 08 '22 19:10

Marlon Alejandro Espinosa Cast


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.

like image 10
Guy Avatar answered Oct 08 '22 20:10

Guy