Within my component, there is a button and a div that contains an input element. The intended behavior is for the div to slide down when the button is clicked, revealing the input field. Clicking the button again should slide the div back up to close it.
However, the current issue is that when the button is clicked, the div opens by sliding up instead of down.
To achieve this animation effect, I am using CSS properties like max-height
and will-change
. How can I correct this unexpected behavior?
You can view the CodeSandbox example here.
Here's the Component code:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [ isOpen, setIsOpen ] = useState( false );
const handleOpen = () => {
setIsOpen( !isOpen );
};
return (
<div className="App">
<button onClick={handleOpen}>Open</button>
<div className={`container ${isOpen ? "containerOpened" : "containerClosed"}`}>
<input type="text" />
</div>
</div>
);
}
And here's the corresponding CSS:
.App {
font-family: sans-serif;
text-align: center;
position: relative;
}
.container {
position: absolute;
bottom: -46px;
right: 0;
margin-right: 30px;
padding: 10px 20px;
background: #fff;
border: 1px solid #e2e2e2;
transition: all 0.3s ease-in-out;
}
.containerClosed {
overflow: hidden;
max-height: 0;
transition: all 0.3s ease;
will-change: transform;
}
.containerOpened {
max-height: 100px;
overflow: hidden;
transition: all 0.3s ease;
will-change: transform;
}
.container input {
border: none;
outline: none;
border-bottom: 1px solid #e2e2e2;
width: 200px;
}
Note that the use of absolute positioning with margin padding on the container is necessary in this case.