Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router—Add/remove Routes at runtime

I have an Application which supports privileges for each user. So if the user has to appropriate permission, he is able to manage users, groups and so on. In case the User hasn't such permission he might not do that.

I have an rest api, with an endpoint, returning all the allowed links for the current user, and with that, I would like to setup the routes for the react-router. In case the permissions are edited and, for instance, the user looses the permission to edit users, the respective Menu Item should disappear from the menu and the route removed from the router. Otherwise a menu item and the route should be added.

Right now I have this setup:

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={Window}>
        <IndexRoute component={Users} />
        <Route path="users" component={Users} />
        <Route path="groups" component={Groups} />
        <Route path="permissions" component={Permissions} />
        <Route path="*" component={Error} />
      </Route>
    </Router>
  </Provider>, mount);

But I really would like to have is: A function which does this setup dynamically and can be run each time Permissions change.

I could not find any documentation about that and I would be glad if there is a way to do that.

UPDATE

According to the given answers and the comments, I realized that the way I wanted to tackle this problem does not go along with the declarative nature of react-router.

like image 872
philipp Avatar asked Jan 04 '23 17:01

philipp


1 Answers

in one of my project i have a following setup, i think you will find it usefull:

componentWillMount() {
  let routes = [];

  routes.push({
    path: '/authenticate',
    component: LoginPage
  });

routes.push({
  path: '/',
  component: Main,
  indexRoute: { component: null },
  getChildRoutes: (error, callback) => {
    getNavigation().then((nav) =>{
      callback(null, getChildRoutes(nav.paths))
    })
  },
  onEnter: () => {
    getNavigation();
    let token = getToken();
    if (token == null || token === '') redirectToAuthenticationUrl();
  }
});

this.routes = routes;

render() {
  return (
    <Router key={uuid()} history={history} routes={this.routes} />
  );
}

You can store your routes in an object, and also pass a promise that will return your routes, you can also check for permissions easily this way. Hope that helps!

like image 54
Mateusz Avatar answered Jan 08 '23 07:01

Mateusz