Skip to content

Instantly share code, notes, and snippets.

@treckstar
Created April 10, 2023 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treckstar/0e497d8489a8fac4f97e305c3350de0a to your computer and use it in GitHub Desktop.
Save treckstar/0e497d8489a8fac4f97e305c3350de0a to your computer and use it in GitHub Desktop.
Set active class using state & withRouter in TypeScript class based components
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