Navigate in code with react-router-dom 4.0?


Keywords:react  router 


Question: 

Looking at this video the react router seems easy to use, but I can't find how to navigate in my code since I want to link on clicking a div and not use <Link>.

I've search StackOverflow but haven't found any answers that work with 4.0. Trying to import browserHistory gives undefined (before and after installing 'react-router' in addition to 'react-router-dom') from this question:

import { browserHistory } from 'react-router';
console.log('browserHistory:', browserHistory);

I also saw somewhere that there is a 'context' you can get to, but this shows a value for 'match' but not 'context':

<Route path="/" render={({ match, context}) => {
    console.log('match:', match);
    console.log('context:', context);

Edit

In the dev tools I can see that "Router" has a history property, so when I add that I can get to it:

<Route path="/" render={({ match, context, history}) => {

Is there a way to get to this from outside a route? For example a navbar component that will navigate to other components, but is not inside a Route itself...


2 Answers: 

If I understand your question, this is how you make a link programaticaly.

    class Test extends React.Component {

      handleClick() {
        console.log(this.context);
        this.context.router.history.push('/some/path');
      },

      render() {

        return (
          <div onClick={handleClick}>
            This is div.
          </div>
        )
      }
    }

    Test.contextTypes = {
      router: React.PropTypes.object.isRequired
    }

    ReactDOM.render(
      <Test />,
      document.getElementById("app")
    );


Had to read into the docs more. The history object is only passed as a property using the component (or other) attributes on a Route. Apparently need to include the 'history' package and use createBrowserHistory and pass it to the Router, then specify the component in a Route. I think this should work fine since exact isn't specified...

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
ReactDOM.render( (
    <Router history={ history }>
      <Route path="/" component={ App } />
    </Router>
  ),
  document.getElementById('root')
);

Before I just had <App/> inside <Router> and didn't have access to those properties.