Search code examples
reactjsstyled-components

Variants with Styled-components


I am building a custom tooltip component and wanted a style for it to be on the top, right, bottom or left of the DOM element. For styling, I am using styled-components. I do not know the best way to set variants of the same element. For now, I have a main style Tooltip and four other component that style the main style (namely, TooltipTop, TooltipRight, TooltipBottom, TooltipLeft). I have tried this:

const variants = {
  top: Styled.TooltipTop,
  right: Styled.TooltipRight,
  bottom: Styled.TooltipBottom,
  left: Styled.TooltipLeft,
};

let TooltipComponent = variants[
   props.direction as keyof typeof props.direction
]
? props.direction
: Styled.TooltipTop;

But then when using the component on the render function it throws:

JSX element type 'TooltipComponent' does not have any construct or call signatures.

Do you have any tips on how I can fix this problem or a more elegant way to have variants of styled-components? Thanks for any help you can provide.


Solution

    1. I suppose, you should use variants[props.direction] instead of props.direction to fix this error.
    let TooltipComponent = variants[
       props.direction as keyof typeof props.direction
    ]
    ? variants[props.direction] 
    : Styled.TooltipTop;
    
    1. You can pass the direction as a property to a style component instead of making 4 separate components. Read more about props
    const Tooltip = styled.div`
      /* Adapt the direction based on  prop */
      left: ${props => props.direction === 'something' ? "100px" : "0px"};
      right: ${props => props.direction === 'something' ? "0px" : "100px"};
    `;
    
    render(
      <div>
        <Tooltip direction="something">Normal</Button>
      </div>
    );