Search code examples
reactjsstyled-components

How to split CSS of a single element into multiple functions/variables in styled-components?


I have a component that has a very long list of CSS that handles various items within that element.

export const StyledTable = styled((props) => <Table {...props} />)`
  padding: 20px;
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);

  & tbody .ant-table-column-sort,
  & thead th.ant-table-column-sort {
    background-color: unset;
  }

  & .ant-select .ant-select-selector {
    border-radius: 10px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    color: lightgray;
    height: 50px;
    font-size: 20px;
    display: flex;
    align-items: center;
  }

  & .ant-pagination {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  & .ant-pagination .ant-pagination-total-text {
    color: rgba(102, 220, 141, 1);
  }

  // and another 100 rows bellow
`;

Some of the CSS is for the rows of the table, others are for the columns, another CSS is for various controls of the table (and provides only the main Table Component, so go figure).

Is there a way to somehow split that css into multiple functions/variables and then do something like:

export const StyledTable = styled((props) => <Table {...props} />)`
  padding: 20px;
  
  ${rowsCss}
  ${columnsCss}
  ${controlsCss}
`

And if that is possible, how do I define rowsCss (and the rest)?


Solution

  • You can just use css blocks:

    import { css } from 'styled-components';
    
    const paginationCss = css`
      & .ant-pagination {
        display: flex;
        justify-content: center;
        align-items: center;
      }
    `
    
    export const StyledTable = styled((props) => <Table {...props} />)`
      padding: 20px;
      ${paginationCss}
    `