Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  12] [ 4]  / answers: 1 / hits: 11382  / 5 Years ago, sat, april 20, 2019, 12:00:00

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: 2em;
`;

const SomeDiv = styled.div`
margin: 3em;
`;


How can I make both elements extend those styles?






It's easy enough if they were both <div> or <img>. I could do:



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

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

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

More From » html

 Answers
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


[#7944] Wednesday, April 17, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;