React Nav Bar Click requires 2 clicks to fire active CSS using useState hook

Viewed 26

I have a useState hook that is used to update an index I then use to provide active css when a nav button is clicked. Here is a code sample:

const [activeId, setActiveId] = useState(0);
const handleChangeActiveId = (index: number) => {
        setActiveId(index);
};


const homeClassName = `${style['nav-link']} ${style['active']} nav-item`;
const inactiveClassName = `${style['nav-link']} nav-item`;


<Link id="home" to={`/`} onClick={() => handleChangeActiveId(0)} className={(activeId === 0) ? homeClassName : inactiveClassName}><span className='item-text'></span><i className={'icon-home'} aria-hidden="true"></i><div className={style.texts}>{translatei18(`Dashboard.home`)}</div>
</Link>
{accessCard && accessCard.map((card, index) => 
(<Link key={card.id} to={`/${locale}${card.link}`} id={card.name} onClick={() => handleChangeActiveId(index + 1)} className={(activeId === (index + 1)) ? homeClassName : inactiveClassName}><i className={`${card.icon} item-text`} aria-hidden="true"></i><span className='item-text'>{translatei18(`Dashboard.cardsOptions.${card.id}.displayValue`)}{index}</span><div className={style.texts}>{translatei18(`Dashboard.cardsOptions.${card.id}.displayValue`)}</div></Link>
))}

The issue I'm having is that I always have to click twice in order for the css class to apply. Also, I notice that activeId doesn't get updated right away when I click. Can someone help me fix this issue?

0 Answers
Related