2

I need to wrap a navigational component in React in a div that acts as a link/a (I have an <a></a> nested in the nav item already and can nest another <a></a> within. I need re-route the user to a new route on click of this outer most div that is acting as a wrapper. I have multiple navigational sections and want to use something like an onClick={this.handleNavClick(newRoute)} but am not having any success. I am console logging the correct linkPath but nothing happens on click.

Here is my function:

  handleNavClick(linkPath) {
    console.log(linkPath)
    let currentPath = window.location.pathname;
    currentPath =  window.location.linkPath;
  },

Here is an example of me trying to re-route from a nav section:

 getNavItem() {
        const currentPath = window.location.pathname;
        const reportPath = "/reporting";

        return (
          <div onClick={this.handleNavClick(dashboardsPath)}>
            <li id="nav-item-view" className={ classNames({"active": currentPath === reportPath}, "sidebar-item")}>
              <div className="active-carat"></div>
            </li>
          </div>
        );
      },
sftaco
  • 75
  • 1
  • 7

2 Answers2

2

You should try something like this:

   onClick={() => {this.handleNavClick(dashboardsPath)}}
Alex Borodin
  • 1,555
  • 12
  • 26
  • I'd recommend [against this though](https://stackoverflow.com/questions/36677733/why-jsx-props-should-not-use-arrow-functions) – Ezz Jul 28 '17 at 00:06
  • @Ezz yes, you are right. But Facebook confirmes this method in it's docs. https://facebook.github.io/react/docs/handling-events.html so it's ok if we have no issues with performance. – Alex Borodin Jul 28 '17 at 00:38
1

This is because onClick accepts a function, but here you're passing the result of a function.

You can do something like this

 getNavItem() {
    const currentPath = window.location.pathname;
    const reportPath = "/reporting";

    const handleNavClick = () => {
      let currentPath = window.location.pathname;
      currentPath =  dashboardPath;
    };

    return (
      <div onClick={handleNavClick}>
        <li id="nav-item-view" className={ classNames({"active": currentPath === reportPath}, "sidebar-item")}>
          <div className="active-carat"></div>
        </li>
      </div>
    );
  },

However I'd avoid creating a handler on every render for performance reasons. You should instead create a NavItem component with it's own handleNavClick method and dashboardPath prop.

Ezz
  • 534
  • 2
  • 8
  • 17