Search code examples
reactjsreact-bootstrapstyled-components

For styled components, how can I make all component styles cascade to .hover component styles?


For instance, if I have the following:

import styled from "styled-components";
import Button as BootstrapButton from "react-bootstrap/Button";

export const Button = styled(BootstrapButton)`
  background-color: rgb(0, 132, 137);
  border-color: rgb(0, 132, 137);
  &:hover {
    background-color: rgb(23, 112, 115);
    border-color: rgb(0, 132, 137);
  }
`;

I have to repeat border-color for both a non-hovered and a hovered button. How can I avoid this duplicate code? Is my only option to create a new styled component as follows?

EDIT: the following doesn't actually work and is the same as above. Still looking for suggestions!

export const Button = styled(BootstrapButton)`
  background-color: rgb(0, 132, 137);
  border-color: rgb(0, 132, 137);
`

export const ImprovedButton = styled(Button)`
  &:hover {
    background-color: rgb(23, 112, 115);
  }
`

In this case, I would use ImprovedButton in my code, but this seems a little verbose (still better than my origin, though). Any thoughts?


Solution

  • Not sure what you're asking. The only reason to declare border-color on hover is if you would want to change the border-color in its hover state.

    See the codesandbox I've created.

    I've added a hover state that will change the border-color to blue on hover.

    If you want to keep the original-border color on hover, simply leave the border-color out of the hover and it will stay black.