title: React - how to trigger function when <Link/> is navigated
body: <p>As you can see in my code, there are many times for triggering the <code>&lt;MenuItem onClick={()=&gt;{closeMainMenu()}}&gt;</code>.</p>
  <p>That's why I want to see if there is any way to avoid this repetitive code</p>
  <p>NarBar.js</p>
  <pre><code>import {
    ProSidebar,
    SidebarHeader,
    SidebarContent,
    Menu,
    MenuItem,
    SubMenu,
  } from &quot;react-pro-sidebar&quot;;
  import { Link } from &quot;react-router-dom&quot;;
  
  import &quot;react-pro-sidebar/dist/css/styles.css&quot;;
  
  import { useSelector, useDispatch } from &quot;react-redux&quot;;
  import { closeMenu } from &quot;../../Redux/actions&quot;;
  
  export default function NavBar(props) {
    const dispatch = useDispatch();
    const showMenu = useSelector((state) =&gt; state.toggleMenu);
  
    const closeMainMenu = () =&gt; {
      dispatch(closeMenu())
    }
    return (
      &lt;ProSidebar
        toggled={showMenu}
        onToggle={() =&gt; {
          closeMainMenu()
        }}
        breakPoint=&quot;md&quot;
      &gt;
        &lt;SidebarHeader&gt;
          &lt;span&gt;Proside Bar&lt;/span&gt;
        &lt;/SidebarHeader&gt;
        &lt;SidebarContent&gt;
          &lt;Menu iconShape=&quot;square&quot;&gt;
            &lt;MenuItem onClick={()=&gt;{closeMainMenu()}}&gt;
              Dashboard
              &lt;Link to=&quot;/&quot; /&gt;
            &lt;/MenuItem&gt;
            &lt;MenuItem onClick={()=&gt;{closeMainMenu()}}&gt;
              General Information
              &lt;Link to=&quot;/general-information&quot; /&gt;
            &lt;/MenuItem&gt;
            &lt;MenuItem onClick={()=&gt;{closeMainMenu()}}&gt;
              blog
              &lt;Link to=&quot;/blogs&quot; /&gt;
            &lt;/MenuItem&gt;
            &lt;MenuItem onClick={()=&gt;{closeMainMenu()}}&gt;
              Users
              &lt;Link to=&quot;/users&quot; /&gt;
            &lt;/MenuItem&gt;
          &lt;/Menu&gt;
        &lt;/SidebarContent&gt;
      &lt;/ProSidebar&gt;
    );
  }
  
  </code></pre>