Search code examples
cssreactjsstyled-components

Conditional width and ellipsis not working on styled component - React.js


My component has a width that should change its size depending on a prop I'm sending to it.

export const PixCodeBox = styled(Box)`
  ${isCopied => css`
    width: ${isCopied ? '170px' : '189px'};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  `}
`;

Not only is the conditional width not working, but the text-overflow: ellipsis is also not working. Does someone know what is wrong with my code? The variable "isCopied" is a boolean that changes its state when I press a button.


Solution

  • You can try this approuch like describe in styled-components documentation without css imports from @emotion/styled:

    export const PixCodeBox = styled(Box)(({ isCopied }) => ({
      width: isCopied ? "170px" : "189px",
      whiteSpace: "nowrap",
      overflow: "hidden",
      textOverflow: "ellipsis"
    }));
    

    or use a condition inside the width property:

    export const PixCodeBox2 = styled(Box)`
      width: ${({ isCopied }) => (isCopied ? "170px" : "189px")};
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    `;
    

    Edit dazziling-code