I have one boolean to control two components (fullPage/halfPage) into one div. when boolean is true fullPage component applied and false halfPage component applied. how can I apply the fadeIn, fadeOut effect on that div. so when fullPage classname applies, full page fade in and half page fade out. when halfPage class name applies, full page fade out and half page fade In?
codesandox.io
// css
.App {
font-family: sans-serif;
text-align: center;
}
.fullPage {
background-color: aquamarine;
animation: fadeIn 2s linear;
width: 490px;
}
.halfPage {
background-color: bisque;
animation: fadeIn 2s linear;
width: 290px;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
// App.tsx
import "./styles.css";
import { useState } from "react";
import classNames from "classnames";
export const HalfPage = () => {
return (
...
)}
export const FullPage = () => {
return (
...
);
};
export default function App() {
const [cnt, setCnt] = useState(0);
const isFullPage = cnt % 2 === 0;
const appClass = classNames({
fullPage: isFullPage,
halfPage: !isFullPage
});
const handleOnClick = () => {
setCnt(cnt + 1);
};
return (
<div className="App">
<button onClick={handleOnClick}>Change background</button>
<div className={appClass}>{isFullPage ? <FullPage /> : <HalfPage />}</div>
</div>
);
}
You can achieve the fade in / fade out effect in both elements, but it requires some refactoring in your HTML code as well as some more CSS to make it work. All we do is wrapping these page elements in divs and place them in a parent element whose class name is inner-container, in order to keep them in the same position as they should be.
So, your new styles.css would look like this (I have pointed out the changes):
.App {
font-family: sans-serif;
text-align: center;
}
/* Added opacity, position and transition time in both elements. */
.fullPage {
background-color: aquamarine;
animation: fadeIn 2s linear;
width: 490px;
opacity: 0;
transition: 0.4s;
position: absolute;
}
.halfPage {
background-color: bisque;
animation: fadeIn 2s linear;
width: 290px;
opacity: 0;
transition: 0.4s;
position: absolute;
}
/* Added flag class for active element and class for inner container. */
.active {
opacity: 1;
}
.inner-container {
position: relative;
}
/* Keyframes are not necessary. */
/* @keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
} */
Your return function in App.tsx would look like this:
return (
<div className="App">
<button onClick={handleOnClick}>Change background</button>
<div className="inner-container">
<div className={isFullPage ? "fullPage active" : "fullPage"}>
<FullPage />
</div>
<div className={isFullPage ? "halfPage" : "halfPage active"}>
<HalfPage />
</div>
</div>
</div>
);