Search code examples
javascriptcssreactjsstyled-components

Styled Components: nesting and referring to other components at the same time


<FooterLight transparent={true}/>

Is it possible to have a nested rule in definition of FooterLight for which the props value transparent is evaluated. Then it assigns 'color: white' to its children ChangelogVersion and CopyRight?

Next two questions:

  1. Since color: white !important is the same for ChangelogVersion and CopyRight. Can these be merged together in one statement?
  2. Does &&& work to not use !important?

export const FooterLight = styled(Navbar).attrs({fixed: 'bottom'})`
  background-color: ${props => props.transparent
  ? 'transparent'
  : 'white'};

  ${props => props.transparent && ChangelogVersion} {
    color: white !important;
  }

  ${props => props.transparent && CopyRight} {
    color: white !important;
  }
`


export const ChangelogVersion = styled(NavLink)`
  &&& {
    font-size: 14px !important;
    padding-right: .5rem;
  }
`

export const CopyRight = styled.div `
  padding: .5rem 0;
  color: '#777777';
  font-size: 14px;
}

Solution

  • Sure can... You could do something like this:

    export const FooterLight = styled(Navbar).attrs({fixed: 'bottom'})`
        background-color: ${props => props.transparent
        ? 'transparent'
        : 'white'};
    
        ${ChangelogVersion}, ${CopyRight} {
             ${props => props.transparent && "color: white !important;"}
        }
    `
    

    As for your second statement, &&& might work but you're better off structuring the CSS better so it doesn't need to be !important in the first place... In you're example there's no reason for any of the importants to be there, so it's hard to offer a suggestion.