SolidJSS
SolidJSโ€ข3y agoโ€ข
7 replies
Razboy20

CSS Transition does not get animated properly when applied in style={} directly

I have a navbar which I have animated (attached), however to achieve this effect I needed to go in a roundabout way.

Basically, the transition needs to switch directions based on which path the user is navigating to, and the issue is that if I compute the transition in the style prop of the div, then the transition updates only after the transition has occurred, rather than influencing the transition. To solve this, I have an effect that sets the style programmatically before the signals are flushed, causing the transition to animate properly.
  createEffect<number>((prevIndex) => {
    setIndicatorDirection(
      (prevIndex ?? getPathIndex()) < getPathIndex()
        ? Direction.RIGHT
        : Direction.LEFT
    );

    const el = indicatorEl();
    if (!el) throw new Error();

    // Question here: Can this be moved into the style instead of within an effect?
    el.style.transition = `left 350ms ${
      indicatorDirection() === Direction.LEFT
        ? 'cubic-bezier(1,0,.3,1) -140ms'
        : 'cubic-bezier(.75,0,.24,1) -40ms'
    },right 350ms ${
      indicatorDirection() === Direction.RIGHT
        ? 'cubic-bezier(1,0,.3,1) -140ms'
        : 'cubic-bezier(.75,0,.24,1) -40ms'
    }`;

    return getPathIndex();
  });


Having a style applied as such:
     <div
          ref={setIndicatorEl}
          style={{
            left: `${offsetLeft}px`,
            right: `${offsetRight}px`,
            transition: `left 350ms ${
              indicatorDirection() === Direction.LEFT
                ? 'cubic-bezier(1,0,.3,1) -140ms'
                : 'cubic-bezier(.75,0,.24,1) -40ms'
            },right 350ms ${
              indicatorDirection() === Direction.RIGHT
                ? 'cubic-bezier(1,0,.3,1) -140ms'
                : 'cubic-bezier(.75,0,.24,1) -40ms'
            }`,
          }}
        ></div>

does not work.

I'm wondering whether there is a better solution to this problem, and whether I am missing a proper method to deal with this sort of issue.

You can view a running copy here: https://stackblitz.com/edit/solid-start-latest-g8yyym?file=src%2Fcomponents%2FNavbar.tsx

Thanks in advance!
Kapture_2023-02-06_at_19.46.25.gif
StackBlitzRazboy20
Vite + solid-start template
Navbar Transitions - StackBlitz
Was this page helpful?