0
votes

I'm using the latest version of react-router (^3.0.0).

I'm trying to create a simple navigation and I'm having trouble to change the component displayed by relation to the url path.

This is my simple routing code:

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

and this is my routes variable:

var routes = (
    <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="authors" component={AuthorPage} />
    </Route>

);

When I navigate to http://localhost:9005/#/authors I still get the App component displayed. I know that my routing does recognize the authors path because if I enter a wrong path (say authors1) then I get an error that the path doesn't exists. I tried using both browserHistory and hashHistory.

So assuming that my routing does recognize the authors path, why it doesn't change the page content according to the authors component?

Thank you

2

2 Answers

1
votes

May be the only problem is that you forgot a slash before authors ("/authors")

ReactDom.render(
    <Router history={browserHistory}>
       <Route path="/" component={App}>
           <IndexRoute component={Home} />
           <Route path="/authors" component={AuthorPage} />
      </Route>    
    </Router>,
    document.getElementById('app')
);

Hope that helps.

0
votes

Use the Match and Miss methods from react-router. Match allows you set rules of the exact component you want to route to and Miss sets the destination if the routing 404's:

import React from 'react';
import {render} from 'react-dom';
import {BrowserRouter, Match, Miss} from 'react-router';
import NotFound from './components/NotFound';

const Root = () => {
    return(
        <BrowserRouter>
            <div>
                <Match exactly pattern="/" component={App} />
                <Match exactly pattern="/authors" component={AuthorPage}/>
                <Miss component={NotFound} />
            </div>
        </BrowserRouter>
    )
}

render(<Root/>, document.querySelector('#main'));