Fallz
Fallz

Reputation: 47

Multiple nested components in styled components

I am fairly new to Styled Components (coming from SCSS), although I get the generally gist of it. I was wondering whether there is a way to consolidate the code below. Although it works, it repeats often. Is there a way to use multiple nested selectors?

const StyledDocuments = styled(Documents)`
  > * > table {
    vertical-align: middle;
  }
  > * > table > tbody {
    vertical-align: middle;
  }
  > * > table > tbody > tr {
    vertical-align: middle;
  }
  > * > table > tbody > tr > td {
    vertical-align: middle;
  }
`;

Many thanks.

Upvotes: 2

Views: 5856

Answers (1)

Agney
Agney

Reputation: 19194

Nesting is directly ported from SASS in styled components and any level of nesting is possible. For example:

const Section = styled.section`
  padding: 4em;
  > * > table {
    border: 1px solid black;
    border-collapse: collapse;
    width: 100%;

    > * > tr {
      text-align: center;
      height: 4rem;
      border: 1px solid red;

      &:first-child {
        color: blue;
      }

      td {
        vertical-align: middle;
      }
    }
  }
`;

See running code https://codesandbox.io/s/jv0o5ykykv

In your specific case, I wonder why you have to nest multiple vertical-align styles when they can automatically be inherited by children when you apply them to the parent table.

For the docs: https://www.styled-components.com/docs/faqs#can-i-nest-rules

Upvotes: 4

Related Questions