React Router + Connected Component

19 February 2019 ·

I just found an issue that I had hard times solving until I saw a comment somewhere on the Internet (can’t find it, sorry).

In a nutshell, after wrapping the first child of ConnectedRouter with connect, weird stuff started happening with my routes.

Consider having this situation:

// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'react-router-redux'
import AppContainer from './containers/app'
import { history, store } from './store'

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <AppContainer />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
)
// WRONG
// containers/app.js
import React from 'react'
import { connect } from 'react-redux';

const AppContainer = ({ foo }) => (
  <div>{ foo }</div>
)

export default connect(() => ({ foo: 'bar' }))(AppContainer);

What you need to do in this case is to wrap your “connected” component with withRouter provided by react-router:

// RIGHT
// containers/app.js
import React from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'

const AppContainer = ({ foo }) => (
  <div>{ foo }</div>
)

export default withRouter(
  connect(() => ({ foo: 'bar' }))(AppContainer)
)

Here you go.

I hope this helps!

Tags:

Might also be interesting for you

Use Elm as a Reducer in Redux

Want to use Elm in your project, but a bit hesitant going cold turkey? In this blog post I'll try to show how you can use the best from both worlds bulletproof Elm logic and ridiculously rich React components library.

Open RSS Reader

I'm starting a new open-source project "Open RSS Reader" that will be modular app so if you don't like the existing clients, you'll be able to quickly build your own. It's gonna be both open source and free to use.

SotM: pet - Awesome Command-line Snippet Manager

`pet` is a simple command-line snippet manager. It allows you to write and store snippets for the command-line, so you don't need to remember all the commands you frequently use in you terminal. It can sync your snippets to the GitHub Gist, so you can always take your snippets with you.

5 Reasons To Give Linux A Try

This time I want to share 5 reasons why I advocate for using Linux whenever I have a chance, and why you should give it a try too.

Comments

comments powered by Disqus