I have a website in which I want to change between different HTML sections, and during these changes that happen in a click of an button I want for the section to for example just fade in.
I made a little test run here is the html:
const [isTestWorking, setIsTestWorking] = useState("test-1");
{isTestWorking == "test-1" && (
<section
className={`test1 ${isTestWorking == "test-1" ? "show" : ""}`}
>
<h1>Testing 1</h1>
<button
onClick={() => {
setIsTestWorking("test-2");
}}
>
Transition
</button>
</section>
)}
{isTestWorking == "test-2" && (
<section
className={`test2 ${isTestWorking == "test-2" ? "show" : ""}`}
>
<h1>Testing 2</h1>
<button
onClick={() => {
setIsTestWorking("test-1");
}}
>
Transition
</button>
</section>
)}
And here is the CSS:
.test1 {
opacity: 0;
transition: opacity 0.8s ease-in-out;
}
.test1.show {
opacity: 1;
transition: opacity 0.8s ease-in-out;
}
.test2 {
opacity: 0;
transition: opacity 0.8s ease-in-out;
}
.test2.show {
opacity: 1;
transition: opacity 0.8s ease-in-out;
}
I expected for this to work just fine but I think that the element gets loaded up onto the website after the animation has already played in the background.
I don’t know what to do know so if you could please help me I would be very grateful.
2
Answers
With copilot I found out that when I use animations instead of the transitions It does finally fade in like I wanted it. Just for reference here is the CSS:
And here is the changed html:
you can introduce a slight delay in changing the state to ensure the transition is seen after the new section has rendered.