1
votes

What seems like a simple integration with react-router-dom has unexpected results. When I click on links in the sidebar, the Link component works correctly by generating the url ie. localhost:3000/about, but I remain on the previous viewing page. When I click on forward and back buttons, the Route renders the correct component.

I am using Webpack, Typescript but don't think those should be affecting anything.

"react": "^16.12.0",

"react-router-dom": "^5.1.2"

    //App Component
    import * as React from 'react';
    import { BrowserRouter as Router, Link, Route } from 'react-router-dom';

    import Sidebar from './Sidebar';
    import Home from './Home';
    import About from './About';
    import Work from './Work';
    import Contact from './Contact';
    import Skills from './Skills';

    const App: React.FC = () => {
      return (
        <Router>
          <div className="main-container">
            <Sidebar />
            <Route exact path="/"><Home /></Route>
            <Route path="/about"><About /></Route>
            <Route path="/skills" component={Skills}></Route>
            <Route path="/work" component={Work}></Route>
            <Route path="/contact" component={Contact}></Route>
          </div>
        </Router>
      );
    };
    //Sidebar Component
    import * as React from 'react';
    import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

    import HomeIcon from '@material-ui/icons/Home';
    import FaceIcon from '@material-ui/icons/Face';
    import WorkIcon from '@material-ui/icons/Work';
    import CodeIcon from '@material-ui/icons/Code';
    import MailOutlineIcon from '@material-ui/icons/MailOutline';

    const Sidebar: React.FC = props => {
      return (
        <Router>
          <nav className="nav-container ">
            <Link to={'/'}><HomeIcon /></Link>
            <Link to={'/about'}><FaceIcon /></Link>
            <Link to={'/skills'}><CodeIcon /></Link>
            <Link to={'/work'}><WorkIcon /></Link>
            <Link to={'/contact'}><MailOutlineIcon /></Link>
          </nav>
        </Router>
      );
    };
1

1 Answers

2
votes

It's because your Sidebar component is wrapped in its own Router. You want your Links and Routes to share the same parent Router. Remove your Sidebar Router and it should fix your problem.

    const Sidebar: React.FC = props => {
      return (
          <nav className="nav-container ">
            <Link to={'/'}><HomeIcon /></Link>
            <Link to={'/about'}><FaceIcon /></Link>
            <Link to={'/skills'}><CodeIcon /></Link>
            <Link to={'/work'}><WorkIcon /></Link>
            <Link to={'/contact'}><MailOutlineIcon /></Link>
          </nav>
      );
    };