Search code examples
reactjsstyled-componentscss-in-js

Styled-components: Styles are not applied when trying to style already styled component


I'm trying to style my component which was styled already. But styles in the new rules are not applied in output CSS.

Can I style component that I already styled?

Thanks you in advance for your help.

EDIT: Add rest of LanugageChooser definition

// COMPONENT THAT I'M TRYING TO STYLE
const LanguageChooser = () => {
    const Container = styled.div`
        display: flex;
        align-items: center;
        height: 36px;
        & > div:not(:last-child) {
            margin-right: 5px;
        }
    `;

    return (
        <Container>
            <Flag { ...languages.pl }/>
            <Flag { ...languages.en }/>
        </Container>
    )
}

const Flag = ({ flag, language }) => {
    const { i18n } = useTranslation();

    const Button = styled.div`
        cursor: pointer;
        font-size: 24px;
        transition: .2s all;
        &:hover {
            font-size: 36px;
        }
    `;

    return (
        <Button onClick={ () => i18n.changeLanguage(language) }>{ flag }</Button>
    )
}
// TRYING ADD MARGIN LEFT, BUT THERE IS NO RESULT.
// ANY OTHER CSS PROPERTY ARE NOT APPLYING
const Navbar = ({ color }) => {
    ...

    const StyledLanguageChooser = styled(LanguageChooser)`
       margin-left: auto;
    `;

    const Nav = styled.nav`
        display: flex;
        align-content:center;
        background: ${ color };
        padding: 2px 3px;
    `;

    return (
        <Nav className="navbar">
            <StyledNavLink to="/home">...</StyledNavLink>
            <StyledNavLink to="/maps">...</StyledNavLink>
            <StyledNavLink to="/charts">...</StyledNavLink>
            <StyledLanguageChooser/>
        </Nav>
    )
}

Solution

  • First, move the styled component outside of function scope or your style will reset on every render and you will get heavy performance issues.

    Secondly, in order to apply styles, you need to pass className property.

    See Styling normal React components

    If you use the styled(MyComponent) notation and MyComponent does not render the passed-in className prop, then no styles will be applied.

    const Container = styled.div`
      display: flex;
      align-items: center;
      height: 36px;
      & > div:not(:last-child) {
        margin-right: 5px;
      }
    `;
    const LanguageChooser = ({ className }) => {
      return (
        <Container className={className}>
          <Flag {...languages.pl} />
          <Flag {...languages.en} />
        </Container>
      );
    };
    
    const Button = styled.div`
      cursor: pointer;
      font-size: 24px;
      transition: 0.2s all;
      &:hover {
        font-size: 36px;
      }
    `;
    
    const Flag = ({ flag, language }) => {
      const { i18n } = useTranslation();
    
      return <Button onClick={() => i18n.changeLanguage(language)}>{flag}</Button>;
    };