简体   繁体   中英

style react router active link

I am using react router 3 for routing. I have tried to develop a generic tab but I have no idea on how should i check if the link is active or not so I can pass it the classname as 'selected'.

Here is my code

const FunctionalTab = ({ items, handleTabKey, ...props }) => {
  console.log("props", props.router);
  return (
    <x-tab>
      <x-tab-item>
        {(items || []).map((item, idx) => (
          <Link key={idx} onClick={() => handleTabKey(item)}>
            {" "}
            {item.name} <br />
          </Link>
        ))}
        <br />
      </x-tab-item>
    </x-tab>
  );
};

const enhance = compose(
  // handler responsible for changing the tab
  withHandlers({
    handleTabKey: props => route =>
      props.router.push(`/commissions/${props.params.id}/details/${route.to}`) // this to be generic 
  })
);

export default withRouter(enhance(FunctionalTab));

For React Router 3 :

You can use the prop activeClassName of the <Link> component. See docs .

Eg:

 <Link
  to="/faq"
  activeClassName="selected"
 >FAQs</Link>

For v4 :

You need to use NavLink instead of Link to style the link according to the matching URL. See NavLink . According to the docs, you have to provide any value to the activeClassName prop of the <NavLink> component.

Eg:

 <NavLink
  to="/faq"
  activeClassName="selected"
 >FAQs</NavLink>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM