Search code examples
javascriptcssreactjsreact-nativestyled-components

How to apply the same props to multiple styled components?


I'm using the styled-components library to extend the header components from the Blueprintjs library. The H6 component currently looks like:

export const DH6 = styled(H6)`
  color: ${(props) => (props.white ? "white" : null)};
  display: ${(props) => (props.flex ? "flex" : null)};
  opacity: ${(props) => (props.opaque ? 0.7 : null)};
  font-weight: ${(props) => (props.heavy ? 500 : 300)};
  text-align: ${(props) => (props.center ? "center" : null)};
  font-style: ${(props) => (props.italics ? "italic" : null)};
  text-decoration: ${(props) => (props.underline ? "underline" : null)};
`;

This works fine. I now want to apply the same props from D1 to D5. Is there a way to do that in DRY fashion, rather than coping over the props? I tried assigning the props to a variable without success:

const generalProps = {
  opacity: ${(props) => (props.opaque ? 0.7 : null)},
  color: ${(props) => (props.white ? "white" : null)},
  display: ${(props) => (props.flex ? "flex" : null)},
  font-weight: ${(props) => (props.heavy ? 500 : 300)},
  text-align: ${(props) => (props.center ? "center" : null)},
  font-style: ${(props) => (props.italics ? "italic" : null)},
  text-decoration: ${(props) => (props.underline ? "underline" : null)}

}

export const DH6 = styled(H6)`
  {...generalProps}
`;

Is there any way to do prop assignment from variables in styled-components?


Solution

  • As an quick example you can use

    import styled, {css} from 'styled-components'
    
    const GlobalStyles = css`
      color: ${(props) => (props.white ? "white" : null)};
      display: ${(props) => (props.flex ? "flex" : null)};
      opacity: ${(props) => (props.opaque ? 0.7 : null)};
      font-weight: ${(props) => (props.heavy ? 500 : 300)};
      text-align: ${(props) => (props.center ? "center" : null)};
      font-style: ${(props) => (props.italics ? "italic" : null)};
      text-decoration: ${(props) => (props.underline ? "underline" : null)};
    `
    
    const StyledDiv = styled.div`
     ${GlobalStyles}
     // Other Styles
    `
    

    What you would do is to import css from the styled-components
    with that you can generate the specific css and return it as a template literal see the document.
    and for reusability you might usually use ${value} that is equivalent for Spread Operator (or{...value}) for styled-components