Home > Enterprise >  react transition group doesn't apply css classes to targeted div
react transition group doesn't apply css classes to targeted div

Time:08-01

It doesn't matter if I use React transition group or tailwind or pure css or any other framework . if I write my simple component like below to show some transition, no transition will happen. here I used react transition group but I have tested others as well and result was the same.

export const OuterComponent = () => {
  const [show, setShow] = useState(false);

  const InnerComponent = () => {
    return (
      <div>
        <CSSTransition 
          in={show}
          timeout={600}
          classNames={"sidebar-transition"}
        >
          <div className="sidebar"></div>
        </CSSTransition>
      </div>
    );
  };

  return (
    <div>
      <InnerComponent />
      <button onClick={() => setShow((prev) => !prev)}>click me</button>
    </div>
  );
};

if I write the component like below everything start working as normal.

export const OuterComponent = () => {
  const [show, setShow] = useState(false);

  const InnerComponent = ({ children }) => {
    return (
      <div>
        <div className="sidebar">{children}</div>
      </div>
    );
  };

  return (
    <div>
      <CSSTransition
        in={show}
        timeout={600}
        classNames={"sidebar-transition"}
      >
        <InnerComponent />
      </CSSTransition>
    </div>
  );
};

another example using tailwind and same result:

export const OuterComponent = () => {
  const [show, setShow] = useState(false);

  const style =
    "w-[100px] h-[60px] transition-all duration-1000 bg-purple-900 text-2xl text-white "  
    (show ? " w-[400px] " : "");

  const InnerComponent = ({ children }) => {
    return (
      <div className={style}> // if I apply style just to this div transition won't work anymore
        {children}
      </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>
  );
};

can someone please give me some Idea what is happening ? I tried almost any solution that came to my mind and the weird part is that I think something simple is happening and I can't understand it.

CodePudding user response:

I found the answer. the problem that is happening here is that the Innercomponent have been declared inside the OuterComponent and on each render it will be reinitialized again and cause some abnormal behavior. to solve the problem I just need to move the InnerComponent outside of definition of OuterComponent and that will work.

CodePudding user response:

You can use the HOC for that. I think this code sandbox will help you I just simply elaborate HOC in react. https://codesandbox.io/s/hoc-in-react-ndvyr7

  • Related