Joey Yi Zhao
Joey Yi Zhao

Reputation: 42500

How to navigate to different route programmatically in `redux-router5`?

I am using redux-router5 in my app to manage routes. I defined the route as below code:

const Root = () => (
    <Provider store={store}>
            <RouterProvider router={router}>
                    <MyComponent />
            </RouterProvider>
    </Provider>
);

router.start((err, state) => {
    ReactDOM.render(<Root/>, document.getElementById('root'));
});

below is the code for store middlewares:

export default function configureStore(router) {

    // create the middleware for the store
    const createStoreWithMiddleware = applyMiddleware(
        router5Middleware(router),
        ReduxPromise,
        ReduxThunk,
    )(createStore);

    const store = createStoreWithMiddleware(reducers);
    router.usePlugin(reduxPlugin(store.dispatch));
    return store;
}

In MyComponent, I can access a router instance through its property but it doesn't have navigate method for me to use. It only has route parameters, name, path, etc. So how can I navigate to a different route inside my component?

Upvotes: 2

Views: 805

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

I've looked into an example

And it seems that it works like this:

import { connect } from 'react-redux';
import { actions } from 'redux-router5'

class SimpleComponent extends React.Component {    
  redirectToDashboard = () => this.props.navigateTo('/dashboard');

  render() {
    return (
      <button onClick={this.redirectToDashboard}>go to dashboard</button>
    )
  }
}

export default connect(null, { navigateTo: actions.navigateTo })(SimpleComponent);

Original answer:

I don't know how to navigate with redux-router5 (at first glance to the documentation it is mainly meant to be used with redux) but to answer your question:

So how can I navigate to a different route inside my component?

Use withRouter HOC from 'react-router':

import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  redirectToDashboard = () => this.props.history.push('/dashboard');

  render() {
    const { match, location, history } = this.props

    return (
      <div onClick={this.redirectToDashboard}>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

Worth to mention that if component is rendered by Route component then it is already "connected" and doesn't need withRouter.

Upvotes: 1

Related Questions