javascriptreactjsreact-routerreact-router-componentreact-routing

How to display a Route by default with React-Router


I'm new to React and I would like to develop a Single Page Application, so I'm using react-router four routing.

Below the main.js, where I specify the routes

import React from 'react';
import {Router,Route} from 'react-router';
import {App} from './components/App';
import {Login} from './components/Login';
import {Home} from './components/Home';
import { history } from 'react-router';

React.render(
<Router history={history}>
    <Route path="/" component={App}>
        <Route path="home" component={Home}/>
        <Route path="login" component={Login}/>

    </Route>
</Router>,
document.getElementById('main')
);

And then the App.js, as you can see I want to have a fixed Header and Footer, and then to have the content of the page change dinamically depending on the route.

import React from 'react';
import {Header} from './Header';
import {Footer} from './Footer';

export class App extends React.Component {


render() {
    console.log(this.props.children);
    return (<div>
        <Header/>
        <div className="page-content">
            {this.props.children}
        </div>
        <Footer/>
    </div>);
}


}

With this code, once the application is loaded with the path ("/"), I need to click on the link Home to display the home content, but I would like to be displayed by default, once the application is first loaded.

How can I achieve that?

Thank you!!


Solution

  • I think you probably want to use an IndexRoute as described here in the React Router documentation.

    Your router would then look something like this:

    <Router history={history}>
        <Route path="/" component={App}>
            <IndexRoute component={Home}/>
            <Route path="login" component={Login}/>
        </Route>
    </Router>