Search code examples
javascriptcssreactjsstyled-components

how to set a active state on a button with styled components - Reactjs


I have a few buttons in my navbar and I want to set an active class with some styles to them when they are clicked. I am using styled components for styling. I have no idea how to set an active state on a button please suggest me how to do it. Below are my codes

style

export const NavButton = styled.button`
  border: none;
  outline: none;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  /* height: 100%; */
  padding: 0.3rem 1.5rem;
  background: transparent;
  cursor: pointer;
  transition: all 0.5s;

  &:hover {
    font-weight: 700;
    background: rgba(204, 204, 204, 0.486);
    border-radius: 0.3rem;
  }
`;

jsx

 <PrimaryNav>
        <NavUl>
          <li>
            <NavButton>Civil</NavButton>
          </li>
          <li>
            <NavButton>Criminal</NavButton>
          </li>
          <li>
            <NavButton>Corporate</NavButton>
          </li>
          <li>
            <NavButton>Service</NavButton>
          </li>
          <li>
            <NavButton>Taxation</NavButton>
          </li>
          <li>
            <NavButton>Acts</NavButton>
          </li>
          <li>
            <NavButton>Notifications</NavButton>
          </li>
        </NavUl>
      </PrimaryNav>

Solution

  • I would use useState to have index of active Element, add text from your buttons to array, then map through the array and add if statement to your Button like this:

     <NavButton active={index === stateIndex ?? true}>{text}</NavButton> 
    

    and then in you styledComponent add prop

    ${({active}) => active && css`
    **Here pass your styling for active element**
    `}