K. Pham
K. Pham

Reputation: 47

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"
  }
}
`;

Upvotes: 0

Views: 1076

Answers (3)

K. Pham
K. Pham

Reputation: 47

I actually did find a method that works and I would love to hear from others with your solution

const PaymentBtnHover = css`
  &:hover {
    background-color: gray;
  }
`;
export const PaymentBtn = styled(Button)`
  margin-left: auto;
  margin-top: 30px;

  ${({ isLoading }) => isLoading && PaymentBtnHover}
`;

Upvotes: 0

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

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.

Upvotes: 2

vatsal soni
vatsal soni

Reputation: 368

export const BaseBtn=styled.button<{isLoading:boolean}>`
....
  isLoading && ::hover{
    background-color: gray;
....
  }
`

I think this might work

Upvotes: 0

Related Questions