CCCC
CCCC

Reputation: 6461

React - how to trigger function when <Link/> is navigated

As you can see in my code, there are many times for triggering the <MenuItem onClick={()=>{closeMainMenu()}}>.

That's why I want to see if there is any way to avoid this repetitive code

NarBar.js

import {
  ProSidebar,
  SidebarHeader,
  SidebarContent,
  Menu,
  MenuItem,
  SubMenu,
} from "react-pro-sidebar";
import { Link } from "react-router-dom";

import "react-pro-sidebar/dist/css/styles.css";

import { useSelector, useDispatch } from "react-redux";
import { closeMenu } from "../../Redux/actions";

export default function NavBar(props) {
  const dispatch = useDispatch();
  const showMenu = useSelector((state) => state.toggleMenu);

  const closeMainMenu = () => {
    dispatch(closeMenu())
  }
  return (
    <ProSidebar
      toggled={showMenu}
      onToggle={() => {
        closeMainMenu()
      }}
      breakPoint="md"
    >
      <SidebarHeader>
        <span>Proside Bar</span>
      </SidebarHeader>
      <SidebarContent>
        <Menu iconShape="square">
          <MenuItem onClick={()=>{closeMainMenu()}}>
            Dashboard
            <Link to="/" />
          </MenuItem>
          <MenuItem onClick={()=>{closeMainMenu()}}>
            General Information
            <Link to="/general-information" />
          </MenuItem>
          <MenuItem onClick={()=>{closeMainMenu()}}>
            blog
            <Link to="/blogs" />
          </MenuItem>
          <MenuItem onClick={()=>{closeMainMenu()}}>
            Users
            <Link to="/users" />
          </MenuItem>
        </Menu>
      </SidebarContent>
    </ProSidebar>
  );
}

Upvotes: 1

Views: 1021

Answers (2)

WebbH
WebbH

Reputation: 2422

If you just want to close the Menu whenever a Link is clicked on, you can create a new component:

const CloseMenu = () => {
  const dispatch = useDispatch();
  const {pathname} = useLocation();
  useEffect(() => {
    dispatch(closeMenu())
  }, [pathname]);
  return null;
};

export default CloseMenu;

and then add that to the top level of your router. Then the menu will close everytime the path changes and you won't need the onclick.

Upvotes: 1

Christian Fritz
Christian Fritz

Reputation: 21364

Why not just create a component?

const MenuLink = ({title, to}) => 
      <MenuItem onClick={()=>{closeMainMenu()}}>
        {title}
        <Link to={to} />
      </MenuItem>;

return ...
  <SidebarContent>
    <Menu iconShape="square">
      <MenuLink title="Dashboard" to="/" />
      <MenuLink title="General Information" to="/general-information" />
      <MenuLink title="blog" to="/blogs" />
      <MenuLink title="Users" to="/users" />
    </Menu>
  </SidebarContent>

Upvotes: 1

Related Questions