Search code examples
javascriptcssreactjsstyled-components

how to use variables conditionally in styled components


I am trying to conditionally change the UI of my component in styled components, but I found myself repeating myself a lot. this is what is happening right now:

color: ${props => (props.isProductPage ? color('white') : 'reset')};
background-color: ${props =>
  props.isProductPage ? color('primary', 'main') : 'reset'};
font-size: ${props => (props.isProductPage ? '1.4rem' : 'reset')};
font-weight: ${props => (props.isProductPage ? '400' : 'reset')};

but I want to have all these in a variable and import that variable conditionally, but I could not find out what am I doing wrong. This is what I am looking for.

const ProductPageAddToCard = `
color: ${color('primary')};
background: ${color('primary', 'main')};
font-size: ${textSize('medium')};
font-weight: ${textWeight('medium')}
`;

export const StyledAddToCardWrapper = Styled.div`
 button {
  ${props => (props.isProductPage ? ProductPageAddToCard : '')}
 }
`

Thanks in advance


Solution

  • You can use the 'css' export from 'styled-components' to create a reusable mixin. Here is a small example:

    import styled, { css } from "styled-components";
    
    // ...
    
    const ProductPageMixin = css`
      color: red;
      background-color: orange;
    `;
    
    const HomePageMixin = css`
      color: blue;
      background-color: yellow;
    `;
    
    const Wrapper = styled.div`
      ${(props) => props.isProductPage && ProductPageMixin}
    
      ${(props) => props.isHomePage && HomePageMixin}
    `;