3

Using React, Redux and React-router, I want to to bind different components to the same route depending on the redux state. for example:

Assuming ComponentA and ComponentB are React components

Assuming I have this redux state

{
  flag: true;
}

I want to have this React Router configuration /routes.js

<Route path="/" component={App}>
  <Route path="/test" component={ComponentA} />
</Route>

but if I have the flag in my Redux state to be false I want to have

...
  <Route path="/test" component={ComponentB} />
...

I am aware that I can create a wrapper component to ComponentA and ComponentB that checks the redux state and then render the corresponding component, but I was searching for an answer that doesn't require creating new components

1 Answer 1

1

You can use a terinary operator in the component field of route.

<Route path="/test" component={flag ? ComponentA : ComponentB} />

Edit: This is how you would map the flag from your state to a prop.

import { connect } from 'react-redux';

// ... Component Definition

const mapStateToProps = (state, ownProps) => {
  return {
    flag: state.flag
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    // Whatever you want to dispatch
  }
}

const ConnectedComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(YourComponent)

Edit 2: Connecting React Router to Redux using a Provider

const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>
)
Sign up to request clarification or add additional context in comments.

5 Comments

How do you get the flag from the redux state ?
That depends on how the rest of your project looks, but in general you would use the connect HOC from react-redux and map the flag prop in the mapStateToProps function it takes as an argument.
I edited my answer above to show how this can be done.
the <Route> .. is in another file so basically if I do flag? .. flag is undefined
If you want to use the redux state to determine your routes you have to connect it somewhere. I don't know the architecture of your project so I can't tell you where to do this. As long as you have your Router wrapped in a Provider component you should have access to the redux store. You should have something that looks like what I put in my second edit that will allow you to access the state in your route handlers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.