2
votes

I am new to React with Styled Components and have run into the following issue:

If I have 10 Styled Components and each of them have the property: background-color: green;, do I have to write that for each Styled Component? Or is there some way to specify that for all? Thanks.

1
Styled components supports theming, see: styled-components.com/docs/advanced - FRMR
@FRMR can this be used for things other than color? For example: display: flex;? - user14358266
Yes, you can pass variables to represent any CSS value you want. - FRMR
@NickSmith See my answer for detailed descriptions - Peter Lehnhardt

1 Answers

1
votes

There are two ways to accomplish shared styles.

  1. You can further style existing styled components with the styled function, so first declaring a basic styled component with shared styles and defining more specially styled components using it:

    import styled from 'styled-components';
    
    const Base = styled.div`
      background-color: green;
    `;
    
    const StyledComp1 = styled(Base)`
      display: flex;
    `;
    
    const StyledComp2 = styled(Base)`
      display: block;
    `;
    
  2. You can use the styled-components css utility function:

    import styled, { css } from 'styled-components';
    
    const sharedStyles = css`
      background-color: green;
    `;
    
    const StyledComp1 = styled.div`
      ${sharedStyles};
      display: flex;
    `;
    
    const StyledComp2 = styled.div`
      ${sharedStyles};
      display: block;
    `;