I have the following Component:
const StyledH3 = styled.h3`
direction: ${(props) => (props.isRTL ? 'rtl' : 'ltr')};
`;
const H3 = ({ children }) => (
<StyledH3 isRTL={isChildrenRTL(children)}>
{children}
</StyledH3>
);
export default H3;
And I want to extend it's styles, for example in a different file:
import { H3 } from 'components';
const Title = styled(H3)`
background-color: red;
`;
How can I achieve this?
There are a couple of implementation details that you should be aware of, if you choose to use styled-components together with existing CSS. styled-components generates an actual stylesheet with classes, and attaches those classes to the DOM nodes of styled components via the className prop.
styled-components utilises tagged template literals to style your components. It removes the mapping between components and styles. This means that when you're defining your styles, you're actually creating a normal React component, that has your styles attached to it.
You need to expose the className prop on your exported component so it can receive the new className:
const StyledH3 = styled.h3`
direction: ${(props) => (props.isRTL ? 'rtl' : 'ltr')};
`;
const H3 = ({ children, className }) => ( // Note - className prop.
<StyledH3
className={className} // Need to add this here
isRTL={isChildrenRTL(children)}
>
{children}
</StyledH3>
);
export default H3;
Then you can extend your component styles in a different file as you have suggested:
import H3 from 'components';
const Title = styled(H3)`
background-color: red;
`;
Reference link https://www.styled-components.com/docs/basics#styling-any-components
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