Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Changes URL, but BrowserRouter doesn't change Viewed Component

The project I am working on is kinda of sensitive, but here's what I have that I can show you all.

The Default Domain

When I click on one of the s in my NavBar, it changes the URL, but it does not change the view to the proper component. Does anyone have any idea why? If there's a better way I can phrase this or improve the quality of my questin, let me know.

My render that I return

<NavBar />
<BrowserRouter>
  <div>
    <Switch>
      <Route path="/propertytypes" component={PropertyTypes} />
      <Route path="/entitytypes" component={EntityTypes} />
      <Route path="/associationtypes" component={AssociationTypes} />
      <Route path={Routes.ROOT} component={Test} />
    </Switch>
  </div>
</BrowserRouter>

My NavBar

import React, { Component } from "react";
import { Link } from "react-router-dom";

class NavBar extends Component {
  render() {
    return (
      <div>
        <ul>
          <li>
            <Link to="/propertytypes">Props!</Link>
          </li>
          <li>
            <Link to="/entitytypes">Ent!</Link>
          </li>
          <li>
            <Link to="/associationtypes">Ass!</Link>
          </li>
        </ul>
      </div>
    );
  }
}

export default NavBar;

After clicking Props link enter image description here

like image 592
drewkiimon Avatar asked Dec 18 '22 21:12

drewkiimon


2 Answers

Besides what @Ukasyah noticed about disparity between the Router you are using (you say you are using BrowserRouter) and the screen captures with the URL you are getting (that points out you are using HashRouter), you must be getting a problem with the code you are showing up because the <Link> component in order to work must be contained inside the BrowserRouter. In your browser console it must be happening this error:

Warning: Failed context type: The context router is marked as required in Link, but its value is undefined.

So to avoid the problem and links start to work, your render should be something like this:

<BrowserRouter>
  <div>
    <NavBar />
    <Switch>
      <Route path="/propertytypes" component={PropertyTypes} />
      <Route path="/entitytypes" component={EntityTypes} />
      <Route path="/associationtypes" component={AssociationTypes} />
      <Route path={Routes.ROOT} component={Test} />
    </Switch>
  </div>
</BrowserRouter>

Note that I put the NavBar component inside the div because BrowserRouter only allows to have a single child.

like image 91
Dez Avatar answered Dec 28 '22 11:12

Dez


I have been looking at different SO questions to solve this issue and none of them helped. My problem was using BrowserRouter in multiple different components. Same as here.

like image 43
Mehmet Ataş Avatar answered Dec 28 '22 09:12

Mehmet Ataş