Skip to content
Advertisement

React routing to endpoint but not rendering content

I can route to another endpoint, but the component content only appears on manual refresh.

I’ve seen this question asked here, here, and I’ve been checking out the reactrouter docs, amongst others. The solution always seems to be “add withRouter” or “make sure you’re wrapping it in Router. I’ve done those things, but sadly got no where.

Here’s the code:

App.js

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

function App() {
  return (
    <Router>
      <Provider store={store}>
        <div className="App">
          <NavBar />
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/account" component={Account} />
          </Switch>
        </div>
      </Provider>
    </Router>
  );
}

NavBar.js

import { BrowserRouter as Router, Link } from "react-router-dom";
import { withRouter } from "react-router";

function NavBar() {
  return (
    <Router>
      <div className="navbar">
        <h3>Connectory</h3>
        <div className="buttons-container">
          <Link>
            <button>Settings</button>
          </Link>
          <Link to="/account"> // successfully redirects to /account, but doesn't render Account page content until refresh
            <button>Account</button>
          </Link>
        </div>
      </div>
    </Router>
  );
}

export default withRouter(NavBar);

EDIT: After comment suggestions, here’s a code sandbox link and here;s the Account.js page:

import React from "react";

export default function Account() {
  return (
    <div>
      <h3>This is the Account page</h3>
    </div>
  );
}

Advertisement

Answer

The Problem here is that, in your Navbar.js, you are re-setting your Routes again when they are already set in App.js.

  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/account" component={Account} /> // Route for Applicatin set here
  </Switch>

You do not need to do that again in. Check here.

https://codesandbox.io/s/gracious-germain-7fyry?file=/src/Navbar.js

Your Nabar should look like:

function NavBar() {
  return (
    <div className="navbar">
      <h3>Connectory</h3>
      <div className="buttons-container">
        <Link to="/">
          <button>Settings</button>
        </Link>
        <Link to="/account">
          <button>Account</button>
        </Link>
      </div>
    </div>
  );
}
Advertisement