I'm working with a div that displays text fetched from an API call. I'm trying to implement a See more
button if the text exceeds 3 lines. Here is my approach:
seeMore(){
this.setState({
seeMore: !this.state.seeMore
})
}
Within the render method
function countLines() {
var el = document.getElementById("about");
var divHeight = el && el.offsetHeight;
var lines = divHeight / 24;
return lines;
}
//assuming 24 as line height.
Inside the return statement
<div>
<div id="about" style={{WebkitLineClamp:seeMore ? '':3}}>
{expert.bio}
</div>
{expert.bio !== undefined && (countLines() >= 3 &&
<span onClick={this.seeMore.bind(this)}>{seeMore === true ? 'See less': 'See more'}</span>)}
</div>
In my current implementation, the offsetHeight
always returns 0 even when the content is present inside the div. I have added a check to only run the countLines
function when there is content available, but it still gives me a 0 value for offsetHeight
.
This solution works fine with hardcoded values, but fails when dealing with text retrieved from the API.