3

I'm trying to get a react router to work. This is my code:

var hashHistory = require('react-router-dom').hashHistory;
var BrowserRouter = require('react-router-dom').BrowserRouter;
var Route = require('react-router-dom').Route;
var ReactDOM = require('react-dom');
var React = require('react');
var Index = require('./index');
var Login = require('./login');

ReactDOM.render(
    <BrowserRouter history={hashHistory}>
        <div>
            <Route path="/" component={Index} />
            <Route path="/login" component={Login} />
         </div>
    </BrowserRouter>,
    document.getElementById('main-content')
);

and then later in my index.js i do this:

 <div className="navbar-nav" onClick={() => this.props.history.push('/login')}>
                    Log in
                </div>

This makes the url change to /login but it doesn't render the login file. What is wrong?

Daniel Gustafsson
  • 1,725
  • 7
  • 37
  • 78

2 Answers2

3

It seems like when you switch to /login it matches to /:

<Route path="/" component={Index} />

Try to add exact prop to the route, like this:

<Route exact path="/" component={Index} />

What you can also try to do is to change the matching order:

<Route path="/login" component={Login} />
<Route path="/" component={Index} />
glennreyes
  • 2,281
  • 16
  • 19
0

Is your index.js a separate file or component? If so you need to use the router middleware to connect it to react-router.

Either import the Link component and use it directly, or bind a click handler and wrap withRouter to mount the router calls to the props.

import React from 'react';
import {Link, withRouter} from 'react-router';

class Test extends React.Component {

    constructor(props) {
        super(props);
        this.handleLink = this.handleLink.bind(this);
    }

    handleLink() {
        this.props.history.push('/login')
    }

    render() {
        return (
             <div>
                 <Link to={{pathname: '/login'}}>Link</Link>
                 <button onClick={this.handleLink}>Click</button>
             </div>
        );
    }

 }

 export default withRouter(Test);
sidonaldson
  • 24,431
  • 10
  • 56
  • 61