I have a container with no height attribute (the height is as large as the content that fills it) and I am changing the text content within that container which ultimately changes the height. I am trying to figure out how I can put a transition on the container for when the height changes. I can't initialize a height on the container because this.state.text is going to be dynamic and the text that it will be changing to will be dynamic as well. The current code I have right now shows no transition on when the height of the container changes. Here is a simple example to show you what I'm talking about.
Here is the Component:
import React, { Component } from "react";
export default class Test extends Component {
constructor(props) {
super(props);
this.state = {
text: "Item 2",
};
}
changeText = () => {
this.setState({
text:
"A much longer text@@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@ @@@@@ @@@@ @@@@@@ @@@@ @@@@@ @@@@@@ @@@@@@@ @@@@@@@@@@ @@@@ @@@@ @@@@@@@@@@@@@@@!",
});
};
render() {
return (
<div>
<div className="text">
<div className="item1">Item 1</div>
<div className="item2">{this.state.text}</div>
<div className="item3">Item 3</div>
</div>
<button onClick={this.changeText}>Click</button>
</div>
);
}
}
Here is the css:
.text {
background-color: yellow;
max-width: 300px;
transition: all 3s ease-out;
}
You could wrap the item in a paragraph element, set the height of the div to 0, and hide the overflow. After injecting the text you can set the height of the div to the height of the paragraph.
<!DOCTYPE html>
<html>
<head>
<title>ok.</title>
<style>
div {
outline: 1px solid black;
transition-property: height;
transition-duration: 1s;
height: 0;
overflow: hidden;
}
p {
margin:0;
}
</style>
</head>
<body>
<div>
<p>Item 1</p>
</div>
<button id="button1">insert short</button>
<button id="button2">insert long</button>
<script>
let div = document.getElementsByTagName("div")[0]
let para = document.getElementsByTagName("p")[0]
let button = document.querySelector("#button1")
button.addEventListener("click", function() {
para.innerHTML ="oneliner"
div.style.height = para.scrollHeight +"px"
})
let button2 = document.querySelector("#button2")
button2.addEventListener("click", function() {
para.innerHTML ="tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, \
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo \
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse \
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non \
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
div.style.height = para.scrollHeight +"px"
})
</script>
</body>
</html>