Created
September 18, 2017 17:13
-
-
Save kdipaolo/48a99972a4ad5d82596defb86613e580 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example url: http://localhost:3000/project/26/details | |
const StyledLink = styled(Link)` | |
border: 2px solid green; | |
${props => | |
props.active && | |
css` | |
border: 2px solid red; | |
`} | |
` | |
class ProjectDetail extends React.Component { | |
state = { | |
activeTab: 'documents' // Set to show documents tab by default | |
} | |
handleLinkClick = e => { | |
this.setState({ | |
activeTab: e.target.innerHTML.toLowerCase() | |
}) | |
} | |
render() { | |
<div> | |
<StyledLink | |
to={`/project/1/details`} | |
active={activeTab === 'details'} | |
onClick={this.handleLinkClick}> | |
Details | |
</StyledLink> | |
<StyledLink | |
to={`/project/2/documents`} | |
active={activeTab === 'documents'} | |
onClick={this.handleLinkClick}> | |
Documents | |
</StyledLink> | |
<StyledLink | |
to={`/project/3/discussion`} | |
active={activeTab === 'discussion'} | |
onClick={this.handleLinkClick}> | |
Discussion | |
</StyledLink> | |
</div> | |
} |
.attrs
essentially lets you pre-set props. So .attrs({ activeClassName: 'active' })
is equivalent to calling the component like <StyledLink activeClassName="active" />
. If you look at the docs for NavLink
, activeClassName
is a prop you can set to determine what class gets applied when the route is active. I'm using "active" as that class name (although, now that I re-read the documentation, I see that's also the default...oh well).
Gotcha! Makes sense. Thanks for your help!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow yes that makes total sense. Throughout i was thinking there had to be a better solution because i felt like I could handle the work with the router/url instead of bringing in state.
NavLink
works perfectly in this scenario!Just curious what value does
.attrs({ activeClassName: 'active',})
bring?Thanks again!