3

I have a react component where I am trying to implement a fading css effect as the user scrolls through a list of components. The component code is here below:

function TypeContainer(props: Props) {
  const ref = useRef<HTMLDivElement | null>(null);
  const entry = useIntersectionObserver(ref, { threshold: 0.5 });
  const isVisible = !!entry?.isIntersecting;
  const ratio = entry?.intersectionRatio;
  return (
    <Card
      onClick={() => props.onClickAddNewType(props.type)}
      ref={ref}
    >
      <Image
        src={icon}
        w="24px"
        h="26px"
        style={{
          transition: 'opacity 0.5s',
        }}
      />
      <Text
        css={TextStyles}
      >
        {title}
      </Text>
    </Card>
  );
}

const TextStyles = css`
  font-style: normal;
  font-weight: 500;
  font-size: 12px;
  line-height: 18px;

  display: flex;
  align-items: center;
  text-align: center;
  letter-spacing: -0.5px;
  margin-top: 16px;
`;

const Card = chakra('div', {
  baseStyle: {
    borderRadius: '10px',
    w: '105px',
    h: '105px',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    cursor: 'pointer',
    minW: '105px',
    background: 'linear-gradient(to right, white, white), linear-gradient(to right, red , white)',
    backgroundClip: 'padding-box, border-box',
    backgroundOrigin: 'padding-box, border-box',
    border: '1px solid transparent',
  },
});

The desired effect is the part of this component when out of viewport should have a fading css effect. The border, image and text for this component.

Lets say: the right side partially out of viewport. I would like to make the entire right side faded. I was thinking of getting the ratio from this hook https://usehooks-ts.com/react-hook/use-intersection-observer to get the threshold of how much I want the image to fade.

I am probably making this css too much complicated. If there's a simpler solution to this problem please advice. To note, I have added overflow: scroll to the wrapper of this element to make sure the list of elements are scrollable when overflown. Thanks!

Zahin
  • 307
  • 3
  • 12

0 Answers0