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;
`;
One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.
If you wish to style your own existing (or any third-party) React component, then you can simply use the styled-components' styled() constructor. This works as long as the React component you're styling attaches the passed className prop (or style prop, if you're using react-native ) to the DOM element.
You can override an existing styled-components component by passing it to the styled() constructor/wrapper. For example, suppose you have the following styled button element: const Button = styled.
Finally, you can use styled-components with any CSS framework. For example, let's create a Button component with Bootstrap styling. We used the attrs method to add a className attribute to the component with btn btn-primary value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With