fridays / next-routes

Universal dynamic routes for Next.js
MIT License
2.47k stars 230 forks source link

How to find if a particular route is Active? #208

Closed williamli closed 6 years ago

williamli commented 6 years ago

I got router from withRoute, but how do I find the actual computed href so I can run a comparison?


class NavLinkComponent extends React.Component {

  render() {
    const componentName = "NavLinkComponent";

    const { activeClassName, className, children, router, ...props } = this.props;

    const thisRoute = _.findWhere(routes, { name: props.route });
    // const isActiveRoute = router.asPath === 

    console.log('current router:', router);
    console.log('props', props);
    // console.log('this route', thisRoute);
    // console.log('router is at this route?', )

    return (
      <Link {...props}>
        <a
          className={classNames(componentName, className, {
            // [`${activeClassName}`]: router.asPath === href
          })}

          {...props}
        >
          {children}
        </a>
      </Link>
    )

  }

}

NavLinkComponent.propTypes = {
  activeClassName: PropTypes.string.isRequired,
}

NavLinkComponent.defaultProps = {
  activeClassName: "active"
}

export default withRouter(NavLinkComponent);
williamli commented 6 years ago

maybe expose the function that you use to computehref taking in route and params will help.

williamli commented 6 years ago

found a solution using routes.findAndGetUrls(...)

screen capture on 2018-07-08 at 12-38-35

// routes

routes.add({ name: 'about', pattern: '/about/:slug?', page: 'index' })
<NavLinkComponent prefetch route="about" params={{ slug: "hello", name:"william"}}>
   about william
</NavLinkComponent>
<NavLinkComponent prefetch route="about" params={{ slug: "hello", name:"john"}}>
   about john
</NavLinkComponent>
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';

import routes, {Link} from '/routes';
import { withRouter } from 'next/router';

class NavLinkComponent extends React.Component {

  render() {
    const componentName = "NavLinkComponent";

    const { activeClassName, className, children, router, ...props } = this.props;

    const isActiveRoute = (props.route === undefined) ? false : routes.findAndGetUrls(props.route, props.params).urls.as === router.asPath;

    return (
      <Link {...props}>
        <a
          className={classNames(componentName, className, {
            [`${activeClassName}`]: isActiveRoute
          })}

          {...props}
        >
          {children}
        </a>
      </Link>
    )

  }

}

NavLinkComponent.propTypes = {
  activeClassName: PropTypes.string.isRequired,
}

NavLinkComponent.defaultProps = {
  activeClassName: "active"
}

export default withRouter(NavLinkComponent);