Ahmed Soliman
Ahmed Soliman

Reputation: 365

How to Bind different react components with the same react-router route depending on redux state?

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

Upvotes: 3

Views: 415

Answers (1)

Dakota
Dakota

Reputation: 1274

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>
)

Upvotes: 1

Related Questions