Wrong component is being rendered using react router

Viewed 50

when I´m trying to navigate to the folowing url http://localhost:3000/alunos/adicionar-aluno but it renders the component {Detail Student} with empty values instead of the proper component { FormAddStudent }. I´m new to react so not sure what I´m doing wrong, I´m trying to use the exact prop but without success.

Here is the code:

  <Router>
  <CssBaseline />
  <div className="App" className={classes.root}>
    <Header />
    <MenuContainer />
    <Switch>
      <Route path="/" exact />
      <Route path="/alunos" exact component = { ListStudents }/>
      <Route path="/contratos" exact component = { ListContracts }/>
      <Route path="/turmas" exact component = { ListClasses }/>
      <Route path="/estagios" exact component = { ListInterships }/>
      <Route path="/formadores" exact component = { ListInstructors }/>
      <Route path="/analise-seguros" exact component = { ListInsurances }/>
      <Route path="/alunos/:id" component = { DetailStudent }/>
      <Route path="/alunos/adicionar-aluno"  exact component = { FormAddStudent }/>
    </Switch>
  </div>
</Router>

Thanks in advance!

1 Answers

React Router starts from the top and look for the first matching route. exact prop does not stop React router from rendering all matching routes ,it only ensures one matcing route is rendered.In your case you have two matching routes:

  • /alunos/:id
  • /alunos/adicionar-aluno

It first catches /alunos/:id and renders component associated for that route.So the order of the routes is important in this case.As @HalilC mentioned in comments,switching the order of routes will solve your problem.

Related