Mel
Mel

Reputation: 61

How can I apply the same styled components pattern to multiple svg components which already exist?

I've already seen how the same styles can be used for multiple components (as shown here) by making one component based on a previously made one, but that same logic doesn't seem to fit my case.

I imported my svg like this:

import { ReactComponent as UpsetEmoticon } from '../images/upset-emoticon.svg';

and used styled components to change the hover color like this:

const UpsetEmoticonStyled = styled(UpsetEmoticon)`
    & path {
        fill: white;
    }
    &:hover {
        & path {
            fill: gray;
        }
    }
`;

I want to apply this same styling to multiple svgs that I'm importing the same way. I could just repeat the code multiple times, switching out the SVG taken in styled() but if there is a way that's more concise I'd prefer that. Thank you in advance!

Upvotes: 1

Views: 386

Answers (1)

Tal Ohana
Tal Ohana

Reputation: 1138

There are couple of ways to tackle this.

  1. If they are in the same hierarchy, you can lift the styles to a common ancestor
const Wrapper = styled.div`
  svg {
    & path {
      fill: white;
    }
    &:hover {
      & path {
        fill: gray;
      }
    }
  }
`;

export default function App() {
  return (
    <Wrapper>
      <IconA />
      <IconB />
    </Wrapper>
  );
}
  1. Use styled-component's as prop
const StyledIcon = styled.svg`
    & path {
      fill: blue;
    }

    &:hover {
      & path {
        fill: gray;
      }
    }
`;

export default function App() {
  return (
    <div>
      <StyledIcon as={IconA} />
      <StyledIcon as={IconB} />
    </div>
  );
}

Upvotes: 1

Related Questions