简体   繁体   中英

How do you pass a prop to all react routes? (Change title dynamically)

I am using redux to manage state, so I'm passing state and bound actions from the root component.

I am using react-router-redux 's ConnectedRouter , with a switch inside containing all my routes and redirects. And I'm trying to prevent passing a setRouteTitle along with the routeTitle . The router switch is similar to the code below.

<Switch>
  <Route
      exact 
      path="/" 
      component={ Dashboard }
      routeTitle="Dashboard"
      setRouteTitle={ setRouteTitle }
      dashboardState={ state.dashboard }/>

  <Route
      exact 
      path="/gear" 
      component={ Gear }
      routeTitle="Gear Management"
      setRouteTitle={ setRouteTitle }
      gearState={ state.gear }/>

  <Route
      exact 
      path="/users" 
      component={ Users }
      routeTitle="Users Management"
      setRouteTitle={ setRouteTitle }
      usersState={ state.users }/>
</Switch>

It just seems redundant to first pass a function and its parameter for the component to run as soon as it will mount/has props, then second defining it on every single route.

Any way to do this without creating a new component that extends Route or something, or would this be a good idea?

Perhaps you can create a wrapper component for Route

// make sure 'setRouteTitle' is in the scope of MyRoute
// and routeProps has the structure = { component, routeTitle, ...etc  }
function MyRoute ({ ...routeProps }) => (
  <Route
    exact 
    path="/" 
    setRouteTitle={setRouteTitle}
    {...routeProps}
  />
);

So that your switch component would be more succinct, like the following:

// in js 
const setRouteTitle = /* some value */
const dashboardProps = { component: Dashboard, routeTitle: 'Dashboard', dashboardState: state.dashboard } 
const gearManagementProps = { component: Gear, /* ... the rest of props */ }
const userProps = { component: User, /* ... the rest of props */ }

// jsx in your render
<Switch>
  <MyRoute {...dashboardProps} />
  <MyRoute {...gearManagementProps} />
  <MyRoute {...userProps} />
</Switch>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM