Home > OS >  Hover a styled component change the color of a child icon
Hover a styled component change the color of a child icon

Time:04-27

I want to create a button with an icon inside, so that when I hover, the icon and button colors change. I tried like this, but only the button color change:

Icon:

    export const InsideIcon= ({ color, ...props }: MyIconSvgFile): JSX.Element => (
  <svg width="16" height="14" viewBox="0 0 16 14" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path
      fillRule="evenodd"
      clipRule="evenodd"
      d="M7.26505 7.1H1.26984V8.9H7.26505V7.1ZM14.7302 8.9H8.73489V7.1H14.7302V8.9ZM8.73489 10.1H14.7302V12.1905H8.73489V10.1ZM1.26984 10.1H7.26505V12.1905H1.26984V10.1ZM1.26984 5.9H7.26505V3.55556H1.26984V5.9ZM14.7302 5.9H8.73489V3.55556H14.7302V5.9ZM16 3.55556V12.1905C16 12.8918 15.4315 13.4603 14.7302 13.4603H1.26984C0.568527 13.4603 0 12.8918 0 12.1905V3.55556V1.26984V0H1.26984H14.7302H16V1.26984V3.55556Z"
      fill={color || '#363BC4'}
    />
  </svg>
);

My styled component:

export const MyButton = styled.div`
  cursor: pointer;
  color: ${colors.Black};
  padding: 14px 20px;
  border: 1px solid ${colors.GreyLight};
  margin-left: 10px;
  font-weight: 400;
  border-radius: 12px;
  height: 41px;
  display: flex;
  text-align: center;
  align-items: center;
  background-color: ${colors.White}
  ${InsideIcon}:hover {
      color: ${colors.White}
  };
  :hover {
      background-color: ${colors.Blue100}
  })
`;

Final component

export const FinalComponent = (): JSX.Element => {
     return (
               <>
                 <MyButton onClick={doSomething}>
                    <div>
                      <InsideIcon/>
                      <text style={{ paddingLeft: '5px' }}>
                        Button text
                      </text>
                    </div>
                  </MyButton>
               </>
)};

Someone can help me?

CodePudding user response:

So your actual problem is the question "how to color an svg without path-information". One option to do this is to create an svg-mask of the image:

.my-class {
    mask: url("./path/to/icon.svg") no-repeat;
    mask-size: contain;
    background: black;
}
.my-class:hover { 
    background: blue;  
}

A whole lot of other solutions can be found here

CodePudding user response:

Try to replace

fill={color || '#363BC4'}

with

fill="currentColor"

The svg path will be colored by (inherited) color property.

Otherwise delete the svg's fill property and set color via fill attribute like so:

  ${InsideIcon}:hover {
      fill: ${colors.White}
  };
  • Related