Issue
I'm a junior front-end developer.
Header and footer areas are fixed
I want to dynamically set the height of the "box container".
If this dynamic height is higher than the set height, I want to make it scroll.
If the total height of the device is 600px and the height of the header and footer is 100px, I want to set the height of the "box container" to 400px
I want to make it scroll when the height of the box container goes over the footer element
a PHONE (600px)
-----
HEADER (100px)
-----
BOXCONTAINER (SCROLL) (400px overflow scroll)
-----
FOOTER (100px)
-----
another page
-----
HEADER (100px)
-----
ANOTHER ELEMENT (200px)
BOXCONTAINER (SCROLL overflow scroll) (200px)
-----
FOOTER (100px)
-----
this is example code
<div className="App">
<header>this is header</header>
<div>.... another content....</div>
<div className="boxContainer">
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
<div className="box" />
</div>
<footer>this is footer</footer>
</div>
.boxContainer {
/* how do i get the dynamic height??? */
height: 300px; // or 200px or 500px ...
overflow : scroll;
}
.box {
background-color: red;
width: 100%;
height: 100px;
margin: 10px 0px;
}
.box:nth-child(2n) {
background-color: blue;
}
What should I do?
I thought about adding px values of the header and footer area for every page, subtracting the total height of the device, and giving the content element a fixed height in inline-style. However, using this method, every page had to be set up (because there might be other elements except header and footer). I thought this wasn't the way.
Solution
Without JS and some shinanigans it is hard, but You are using react so You can calculate everything after component did mount and set height of boxContainer acordingly:
componentDidMount(){
const elements = document.querySelectorAll('.App > *:not(.boxContainer)');
var height = 0;
for (const element of elements.values()) {
let style = window.getComputedStyle(element);
height += parseInt(style.height);
}
document.querySelector(':root').style.setProperty('--box-container-height', height+'px');
/*
other way would be using state variable
this.setState({
boxContainerHeight : `calc(100vh - ${height}px)`
}) */
}
Set state is antipattern (it calls render() method second time), so better use css vars. full demo: https://jsfiddle.net/m9rqsL4j/13/
Answered By - Bogdan Kuštan
Answer Checked By - - Pedro (ReactFix Volunteer)