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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With