React Router link isn't working in Menu.Item element in ReactJS & Mobx using react-router-dom

596 Views Asked by At

I'm trying to route in a react app using react-router-dom but it seems there is a problem when I try to put a link in a menu item element it doesn't respond at all.

Here is the code below of navbar.tsx

import React, { useContext } from "react";
import { Menu, Container, Button } from "semantic-ui-react";
import ActivityStore from "../app/stores/activityStore";
import { observer } from "mobx-react-lite";
import { Link } from "react-router-dom";


  const NavBar: React.FC = () => {
  const activityStore = useContext(ActivityStore);
  return (
    <Menu fixed="top" inverted>
      <Container>
        <Menu.Item header as={Link} to='/'}>
          <img src="/assets/logo.png" alt="logo" style={{ marginRight: 10 }} />
          Application Home Page
        </Menu.Item>
        <Menu.Item name="Activities" as={Link} to='/activities' />
        <Menu.Item>
          <Button
            positive
            content="Create Activity"
            as={Link}
            to='/createActivity'
          />
        </Menu.Item>
      </Container>
    </Menu>
  );
};

export default observer(NavBar);

and this is the main layout App.tsx page i'm defining the routing

import { useEffect, Fragment, useContext } from "react";
import { Container } from "semantic-ui-react";
import NavBar from "../../features/nav/NavBar";
import ActivityDashboard from "../../features/activities/dashboard/ActivityDashboard";
import LoadingComponent from "./LoadingComponent";
import ActivityStore from "../stores/activityStore";
import { Route } from "react-router-dom";
import HomePage from "../../features/home/HomePage";
import ActivityForm from "../../features/activities/form/ActivityForm";
import { observer } from "mobx-react-lite";

const App = () => {
  const activityStore = useContext(ActivityStore);

  useEffect(() => {
    activityStore.loadActivities();
  }, [activityStore]);

  if (activityStore.loadingInitial)
    return <LoadingComponent content="Loading activities" />;

  return (
    <Fragment>
      <NavBar />
      <Container style={{ marginTop: "7em" }}>
        <Route exact path="/" component={HomePage} />
        <Route path="/activities" component={ActivityDashboard} />
        <Route path="/createActivity" component={ActivityForm} />
      </Container>
    </Fragment>
  );
};

export default observer(App);

So the question is what is it that I'm doing wrong?

Edit:

I fixed the problem by surrounding Route Components with Switch

            <Switch>
              <Container style={{ marginTop: "7em" }}>
                <Route exact path="/" component={HomePage} />
                <Route path="/activities" component={ActivityDashboard} />
                <Route path="/createActivity" component={ActivityForm} />
              </Container>
            </Switch>

Thank you.

0

There are 0 best solutions below