Home > Enterprise >  Transition doesn't work on child component, but works when applied to the parent component
Transition doesn't work on child component, but works when applied to the parent component

Time:08-01

I'm trying to animate the width of a div of a child component. My code is simple:

    export const OuterComponent = () => {
      const sidebarCtx = useContext(SidebarContext);
    
      const style =
        "w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white "  
        (sidebarCtx.isOpen ? " w-[400px] " : "");
    
      const InnerComponent = ({ children }) => {
        return (
          <div className={style}> // if I apply style just to this div transition won't work anymore
            {children}
            <a>testing</a>
          </div>
        );
      };
    
      return (
        <div className={style}> // if I apply style here and remove the above style on the InnerComponent transition works OK as normal
          <InnerComponent />
        </div>
      );
    };

As explained in the code comments, the problem is that if I apply style to InnerComponent directly, the width change is not animated.

CodePudding user response:

What is happening since you have defined InnerComponent inside OuterComponent, it is reinitiated on each OuterComponent render, and that is probably messing with your animation.

try this:

 const InnerComponent = ({ children, classNames }) => {
        return (
          <div className={classNames}> // if I apply style just to this div transition won't work anymore
            {children}
            <a>testing</a>
          </div>
        );
      };

export const OuterComponent = () => {
      const sidebarCtx = useContext(SidebarContext);
    
      const classNames =
        "w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white "  
        (sidebarCtx.isOpen ? " w-[400px] " : "");
    
    
      return (
        <div className={style}> // if I apply style here and remove the above style on the InnerComponent transition works OK as normal
          <InnerComponent classNames={classNames} />
        </div>
      );
    };

CodePudding user response:

I'm not sure but u can try this.

const style =
    `w-[${sidebarCtx.isOpen ? 400 : 100}px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white`.
  • Related