twind-react icon indicating copy to clipboard operation
twind-react copied to clipboard

Classname not applying on next siblings on styled components

Open saradevh opened this issue 4 years ago • 2 comments

Hi! I'm facing a weird issue when applying padding to siblings div.

What I'm searching to do

Apply padding depending on a prop value (align in my case), and passing this padding through className to a styled component.

The code

I have four Items with various align value:

<Item align="left" />
<Item align="justify" />
<Item align="right" />
<Item align="left" />

textPadding is set depending on align value, and pass via className to StyledItem.

const Item = (props: { align: string }) => {
  const textPadding = props.align === "left" ? "pl-2" : "pr-2";
  return (
    <StyledItem className={tw`${textPadding}`}>
      <NestedContent />
    </StyledItem>
  );
};

StyledItem is a twind/react styled component.

const StyledItem = styled("div", {
  base: `bg-indigo-600 w-full h-7`
});

From here, I should have the 1st and 4th Item components with pl-2 (because align === "left") and the 2nd and 3rd Item components with pr-2 (because align !== "left").

But the result is different: the 4th Item component has pr-2 applied.

Capture d’écran 2021-04-07 à 18 18 46

(screenshot with padding as blue parts)

Reproduced issue in sandbox

https://codesandbox.io/s/relaxed-lederberg-9euwo?file=/src/App.tsx

What do you think? It's because we add style through className to a styled component? Thanks a lot :)

saradevh avatar Apr 07 '21 16:04 saradevh

Thanks a lot for this detailed report!

I can confirm that the behavior is not correct for className properties.

Using the tw prop fixes it:

export const Item = (props: { align: string }) => {
  const textPadding = props.align === "left" ? "pl-2" : "pr-2";
  return (
    <StyledItem tw={textPadding}>
      <NestedContent />
    </StyledItem>
  );
};

But I consider this still a bug.

PS: I would use variants for align: https://codesandbox.io/s/quirky-fast-qlrjr?file=/src/StyledItem.tsx

sastan avatar Apr 08 '21 17:04 sastan

Hi @sastan! Thanks for your answer. I'll use tw instead of className meanwhile.

You're totally right about variants, but in my case StyledItem is a Text component with its own variants, not including padding.

saradevh avatar Apr 13 '21 06:04 saradevh