Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css transition not working on conditional rendering in React

I have a simple checkbox, onClick of which I want to show and hide a div along with some transition delay using React. I can achieve the same effect when not using React. However when I use conditional rendering in react to render the div on click of checkbox. It does not show the effect. Here's the code which I have so far

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [checkBox, setCheckBox] = useState(false);
  return (
    <div className="App">
      <input
        type="checkbox"
        checked={checkBox}
        onChange={() => setCheckBox(!checkBox)}
      ></input>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {checkBox && (
        <div
          style={{
            opacity: 1,
            transition: "height 2s",
            transitionTimingFunction: "ease-in"
          }}
        >
          Hey the checkbox is checked
        </div>
      )}
    </div>
  );
}

Codesandbox link - https://codesandbox.io/s/reverent-cartwright-gk11s?file=/src/App.js:0-659

Any help is much appreciated

like image 611
Brijesh Prasad Avatar asked Jan 31 '26 19:01

Brijesh Prasad


1 Answers

It works for me. Try like this.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [checkBox, setCheckBox] = useState(false);
  return (
    <div className="App">
      <input
        type="checkbox"
        checked={checkBox}
        onClick={() => setCheckBox(!checkBox)}
      ></input>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <div className={checkBox ? "animate show" : "animate"}>
        Hey the checkbox is checked
      </div>
    </div>
  );
}

And in the css file...

.animate {
  height: 0px;
  overflow: hidden;
  transition: height 0.5s;
}
.show {
  height: 18px;
}

Please confirm here.

https://codesandbox.io/s/goofy-moon-ipe7t

like image 50
BTSM Avatar answered Feb 02 '26 10:02

BTSM