Search code examples
cssreactjsstyled-components

Using conditional statements with styled components


I'm trying to style my PaymentBtn which includes my main styled Button but I only want the hover effect to be affected when my isLoading prop is activated while keeping everything the same EXCEPT the hover effect. Is there a way to only change the styling on the hover effect?

Basic button

export const BaseBtn = styled.button`
  min-width: 165px;
  width: auto;
  height: 50px;
  letter-spacing: 0.5px;
  line-height: 50px;
  padding: 0 35px 0 35px;
  font-size: 15px;
  background-color: black;
  color: white;
  text-transform: uppercase;
  font-family: "Open Sans Condensed";
  font-weight: bolder;
  border: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

  &:hover {
    background-color: white;
    color: black;
    border: 1px solid black;
  }
`;

PaymentBtn styles

export const PaymentBtn = styled(Button)`
  margin-left: auto;
  margin-top: 30px;
`;

I want something like this but don't know how to use it with styled-components

export const PaymentBtn = styled(Button)`
  margin-left: auto;
  margin-top: 30px;

&:hover {
 ${({isLoading}) => isLoading ? 
  hover:{
    background-color: "gray" : "black"
  }
}
`;

Solution

  • You can try this:

    export const PaymentBtn = styled(Button)`
      margin-left: auto;
      margin-top: 30px;
    
      &:hover { 
        background-color: ${props => (props.isLoading ? 'gray' : 'black')}
      }
    `;
    

    This will show gray color on hover when isLoading is true, otherwise, it will show black. If you don't want any color on false, set it as transparent.