skip to Main Content

i have a button which used to route.The routes are from api so on my first click the route is working but the button color is not changing

i used useState hook and css for changing the color,it is working perfectly but not on first click

2

Answers


  1. If you project is created using CRA – create react app, you can add activeclassname="active" to your div and in css/scss file add wanted styling.

    import { NavLink } from "react-router-dom";
    
    <NavLink to="/some-route" activeclassname="active">
      text
    </NavLink>
    
     & a {
       color: red
       &.active {
          color: blue;
       }
    }
    
    

    If you project is created using Vite, then you don’t need activeclassname and only add:

    <NavLink to="/some-route">text</NavLink >
    
     &.active {
        color: $blue;
     }
    
    Login or Signup to reply.
  2. I think the button color is not changing on the first click, because the state update is not happening in time to reflect the change in color. This can happen if the state update is asynchronous.

    To ensure that the state update happens immediately, you can use the useEffect hook in combination with the useState hook.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search