redux - How to change index route depending on state -


let's have following main react application, using react-redux , react-router (but not react-router-redux yet):

<provider store={store}>   <router history={hashhistory}>     <route path="/" component={app}>       <indexroute component={loginrequiredpage}/>       <route path="/login" component={login} />       <route path="/entries" component={showentries} />     </route>   </router> </provider> 

in store have state isloggedin , change component of indexroute showentries when isloggedin true , loginrequiredpage if becomes false. i'm not sure how achieve this, can think of several ways:

  1. use react-redux connect method on indexroute map isloggedin new value component property.
  2. create home component, connect store, switch out child component depending on isloggedin , have home new indexroute component

which option better or there better solution?

i'd current view change while index route active , isloggedin state changes.

the straightforward way declare component either return showentries or loginrequiredpage based on value of property of store:

<provider store={store}>   <router history={hashhistory}>     <route path="/" component={app}>       <indexroute component={index}/>       <route path="/login" component={login} />       <route path="/entries" component={showentries} />     </route>   </router> </provider> 

and

@connect(state => ({   isloggedin: ... // <- place correct value here })) class index extends component {   render() {     const {       isloggedin     } = this.props;      if (isloggedin) {       return <showentries />     } else {       return <loginrequiredpage />     }   } } 

another way check if user has logged in per every route enter via onenter prop, , redirect route, means you'll evidently change location user sees in browser. if you're curious, check out this tip.


Comments