Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
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.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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!

over 4 years ago · Santiago Trujillo Relatório

0

You can use the onEnter prop on Route for conditional auth. You can check whether a user has permission to enter the view, and if they don't, navigate them away elsewhere.

See: https://github.com/ReactTraining/react-router/blob/master/docs/API.md#onenternextstate-replace-callback

<Route path='/accounts' component={Accounts} onEnter={isAuth} />

const isAuth = (nextState, replace) => {
  if (!isCurrentUserAuthorised) {
    replace({pathname: '/'});
  }
}  

The isAuth method is entered when navigating to /accounts. Obviously you'd need to put your own logic in for determining if the user is authorised, but that's the jist of it. Just put a pathname of where you'd like unauthorised users to be sent away to.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda