Created
April 10, 2023 19:17
-
-
Save treckstar/0e497d8489a8fac4f97e305c3350de0a to your computer and use it in GitHub Desktop.
Set active class using state & withRouter in TypeScript class based components
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
import React from 'react'; | |
import { withRouter, Router } from 'next/router'; | |
interface IndexProps { | |
router: Router; | |
} | |
interface IndexState { | |
activeLink: string; | |
} | |
class Index extends React.Component<IndexProps, IndexState> { | |
constructor(props: IndexProps) { | |
super(props); | |
this.state = { | |
activeLink: '/', | |
}; | |
} | |
componentDidUpdate(prevProps: IndexProps) { | |
if (this.props.router.pathname !== prevProps.router.pathname) { | |
this.updateActiveLink(); | |
} | |
} | |
componentDidMount() { | |
this.updateActiveLink(); | |
} | |
updateActiveLink() { | |
const { pathname } = this.props.router; | |
this.setState({ activeLink: pathname }); | |
} | |
render() { | |
const { activeLink } = this.state; | |
return ( | |
<div> | |
<nav> | |
<ul> | |
<li> | |
<a href="/" className={activeLink === '/' ? 'active' : ''}> | |
Home | |
</a> | |
</li> | |
<li> | |
<a href="/about" className={activeLink === '/about' ? 'active' : ''}> | |
About | |
</a> | |
</li> | |
<li> | |
<a href="/contact" className={activeLink === '/contact' ? 'active' : ''}> | |
Contact | |
</a> | |
</li> | |
</ul> | |
</nav> | |
<h1>Welcome to my website!</h1> | |
<p>This is a sample website built with Next.js and React.</p> | |
</div> | |
); | |
} | |
} | |
export default withRouter(Index); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment