Search code examples
cssreactjstypescriptnext.jsstyled-components

Changing colour of active bootstrap nav-link using styled component in Nextjs app.(typescript)


I am using react-bootstrap and styled components in my react typescript app. I want change the colour of active nav-link.

code:

const StyledNav = styled(Nav)`
  font-size: 12px;
  text-transform: uppercase;
`;
  <StyledNav>
     <StyledNav.Link>BACK </StyledNav.Link>
     <StyledNav.Link>HOME </StyledNav.Link>
     <StyledNav.Link active>{props.page}</StyledNav.Link>
  </StyledNav>

TIA


Solution

  • You can use props in your template literals.

    const StyledLink = styled(Nav.Link)`
      font-size: 12px;
      text-transform: uppercase;
      color: ${props => props.active ? 'red': 'inherit'};
    `;
    

    If you want to have multiple definitions you can use it like;

    const StyledLink = styled(Nav.Link)`
      font-size: 12px;
      text-transform: uppercase;
      ${props => props.active && `
        color: red;
        border-bottom: 3px solid green;
      `}
    `;
    
      <Nav>
         <StyledLink>BACK </StyledLink>
         <StyledLink>HOME </StyledLink>
         <StyledLink active>{props.page}</StyledLink>
      </Nav>