React component not showing on matched route (react-router-dom)

Hello everyone, I don't know what's going on. I have the following routes:

<BrowserRouter>
  <div>
    <Switch>
      <Route path="/patient/:id/" component={PatientWrapper} />
      <Route path="/patient/:id/patient_profile/admission_form" component={PatientAdmission} />
      <Route path="/patient/:id/patient_profile/discharge_form" component={PatientDischarge} />
      <Route path="/patient/:id/patient_profile/encounter_details" component={PatientEncounterDetails} />
      <Route path="/" component={App} />
    </Switch>
  </div>
</BrowserRouter>

      

Only those who work, only Route with path = "/" and Route with path = "/ patient /: id" work , the other 3 routes simply do not display the component corresponding to the path.

This is how I refer to Route. I have a header component with appropriate links on it. See below

<ul className="dropdown-menu dropdown-messages">
    <li><Link to={"/patient/" + this.props.id +"/patient_profile/admission_form"} id="admission-link" >Admission</Link></li>
     <li><Link to={"/patient/" + this.props.id +"/patient_profile/discharge_form"} id="discharge-link">Discharge</Link></li>
     <li className="divider"></li>
     <li><Link to={"/patient/" + this.props.id +"/patient_profile/encounter_details"} id="encounter-details">Encounter Details</Link></li>
</ul>

      

In the Header component, I import {Link} from "react-router-dom"; and in the file where I declare routes I import {BrowserRouter, Route, Switch} from 'react-router-dom';

What am I doing wrong?

+3


source to share


1 answer


The problem here is that you are not using exact

prop for your parent routes. By default, Route does not perform an exact match. As an example for the way /

how to /

and /patient

treated as a match. So even in your case, /patient/:id/

Route matches all routes of other routes starting with /patient/:id/

. Since Switch only renders the first match, it always renders PatientWrapper even for other paths like /patient/:id/patient_profile/admission_form

.

By using exact

prop as follows, you can explicitly tell the Route exactly.



<BrowserRouter>
  <div>
    <Switch>
      <Route exact path="/" component={App} />
      <Route path="/patient/:id/" exact component={PatientWrapper} />
      <Route path="/patient/:id/patient_profile/admission_form" component={PatientAdmission} />
      <Route path="/patient/:id/patient_profile/discharge_form" component={PatientDischarge} />
      <Route path="/patient/:id/patient_profile/encounter_details" component={PatientEncounterDetails} />
    </Switch>
  </div>
</BrowserRouter>

      

+1


source







All Articles