Skip to content Skip to sidebar Skip to footer

Styled-components: Extend Styles And Change Element Type

Imagine I have the following styles: color: black; border: 1px solid white; and I want to apply them both to two elements of different types: const SomeImg = styled.img` margin:

Solution 1:

You can use prop "as" from styled-components who will change html tag of your component: https://www.styled-components.com/docs/api#as-polymorphic-prop

Below an example of what you want:

const ExtendMe = styled.div`
  color: black;
  border: 1px solid white;
`;

const SomeImg = styled(ExtendMe).attrs({
  as: "img"
})`
  margin: 2em;
`;


const SomeDiv = styled(ExtendMe)`
  margin: 3em;
`;

You can see on : https://codesandbox.io/embed/mj3j1xp6pj?fontsize=14

Post a Comment for "Styled-components: Extend Styles And Change Element Type"