Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style an imported styled-component

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?

like image 701
Asaf David Avatar asked Feb 25 '18 15:02

Asaf David


People also ask

Does styled-components generate CSS?

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.

What is styled in styled-components?

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.


1 Answers

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

like image 88
Cubed Eye Avatar answered Sep 25 '22 09:09

Cubed Eye