0

I have a react/nextjs app and have navigation with Home|account|Jobs. How do I bold the active. item when a user select it from the navigation

Here my navigation snippet

class Header extends React.Component {

    render() {
    
        <ListItem>              
           <Link prefetch href={"/jobseeker/home"}>
               <a>home</a>
            </Link>                  
        </ListItem>
        <ListItem>              
           <Link prefetch href={"/jobseeker/account"}>
               <a>account</a>
            </Link>                  
        </ListItem>
        <ListItem>              
           <Link prefetch href={"/jobseeker/jobs"}>
               <a>jobs</a>
            </Link>                  
        </ListItem>
    }
}
user2570135
  • 2,669
  • 6
  • 50
  • 80
  • I think this the answers here should help: https://stackoverflow.com/questions/53262263/target-active-link-when-the-route-is-active-in-next-js – davbuc Jul 07 '20 at 20:40
  • 1
    Does this answer your question? [Target Active Link when the route is active in Next.js](https://stackoverflow.com/questions/53262263/target-active-link-when-the-route-is-active-in-next-js) – davbuc Jul 07 '20 at 20:40

1 Answers1

1

create a array of objects for each list item and map through that array ,and then when user select it store the index of current tab in state, and apply the styles the according to current index.

class Header extends React.Component {

 constructor(props){
  super(props);

  this.state = {
    currentIndex: null
  }
 }
 const menuData = [
   {
     href:"/jobseeker/home",
     tabContent: "Home"
   },
    {
     href:"/jobseeker/account",
     tabContent: "Account"
   },
    {
     href:"/jobseeker/jobs",
     tabContent: "Jobs"
   },
]

handleSelect = (index) => {
 this.setState({ currentIndex:index });
}


render() {
   const { currentIndex } = this.state;
   
    
   {menuData.map((menu,index) => (
     
      <ListItem key={index} onClick={(() => this.handleSelect(index)}>              
       <Link prefetch href={menu.href}>
           <a className={currentIndex === index ? 'tab-underline':''} >{menu.tabContent}</a>
        </Link>                  
    </ListItem>

    ))}
}}

and then you can create 'tab-underline' css class in your css file and use it.

isa_toltar
  • 586
  • 5
  • 11
  • Thanks, I tried your solution but it did work .. I define an inline style === const activeLink = { fontWeight: 'bold' }. and just release 'tab-underline' with this class – user2570135 Jul 10 '20 at 01:15
  • Yep. it did not worked me me.. The link is not bold when it is active. I add my style in the render function – user2570135 Jul 10 '20 at 11:38