Search code examples
styled-componentsreact-props

Styled component css helper not working with mixin


I want to change the StyledButton depends on the props passed. When complex is true, it's supposed to go to complexMixin and then determine what whiteColor passes. But even I pass whiteColor with true, the color is black, not white.

Does anyone have idea what's going on with it? Thanks!

Demo

import styled, { css } from "styled-components";

const complexMixin = css`
  color: ${({ whiteColor }) => (whiteColor ? "white" : "black")};
`;

const StyledButton = styled.div`
  border: 1px solid red;
  height: 100px;
  text-align: center;
  margin: 20px;
  font-weight: 700;
  font-size: 40px;
  color: ${({ complex }) => (complex ? complexMixin : "green")};
`;

const App = () => {
  const isComplex = true;
  const isWhite = true;
  return (
    <>
      <StyledButton whiteColor={isWhite} complex={isComplex}>
        ccc
      </StyledButton>
      <StyledButton complex={!isComplex}>BBB</StyledButton>
    </>
  );
};

Solution

  • usually, I write this kind of complicated CSS logic like this.

    const complexMixin = css`
      ${({ complex, whiteColor }) =>
        complex &&
        css`
          color: #000;
          ${whiteColor &&
          css`
            color: #fff;
          `}
        `}
      ${({ complex }) =>
        !complex &&
        css`
          color: green;
        `}
    `;
    
    const StyledButton = styled.div`
      border: 1px solid red;
      height: 100px;
      text-align: center;
      margin: 20px;
      font-weight: 700;
      font-size: 40px;
      ${complexMixin}
    `;