Skip to content

Instantly share code, notes, and snippets.

@blehr
Last active September 20, 2018 12:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blehr/a14f187d7ecf88b2e803e92d81069b93 to your computer and use it in GitHub Desktop.
Save blehr/a14f187d7ecf88b2e803e92d81069b93 to your computer and use it in GitHub Desktop.
How to get the bootstrap active class on a links containing <li> when using nav-tabs
/*********************************
* nav-tabs.js
* *******************************/
import React from 'react';
import Tab from './tab';
const NavTab = () => {
return (
<nav>
<ul className="nav nav-tabs">
<Tab to="/" onlyActiveOnIndex >Home</Tab>
<Tab to="/anotherPage" >Another Page</Tab>
<Tab to="/andAgain" >And Again</Tab>
</ul>
</nav>
);
};
export default NavTab;
/*********************************
* tab.js
* *******************************/
import React, { Component, PropTypes } from 'react';
import { Link, IndexLink } from 'react-router';
export default class Tab extends Component {
static propTypes = {
to: PropTypes.string,
onlyActiveOnIndex: PropTypes.bool,
children: PropTypes.node
}
// pull in the router context
static contextTypes = {
router: PropTypes.object.isRequired
};
render() {
// determine if the route is active, router.isActive function
// receives the "to" and onlyActiveOnIndex props
const isActive = this.context.router.isActive(this.props.to, this.props.onlyActiveOnIndex);
// if onlyActiveOnIndex is passed then IndexLink is used, else just Link
const LinkComponent = this.props.onlyActiveOnIndex ? IndexLink : Link;
// add the bootstrap active class to the active links containing <li>
const className = isActive ? 'active' : '';
return (
<li className={className} >
<LinkComponent to={this.props.to} >{this.props.children}</LinkComponent>
</li>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment