Skip to content
Advertisement

React Tailwind Dynamic Div Height Not Updating Post Calculation

I have a screen which has two divs: top navbar (80px in height) and a div component below the navbar (remaining screen height).

Since I am using tailwind formatting looks something like this:

<div className="w-screen h-[80px]"> //navbar
</div>
<div className="w-screen h-screen"> //bottom content div
</div>

The problem, navbar is 80px and bottom content is dynamic but a white gap appears at the bottom. White gap will disappear if using h-screen (100% vw). enter image description here

Because of the navbar’s height of 80px I must dynamic subtract the bottom div (h-screen-80px) otherwise a vertical scroll bar will appear which I dont want. So I have a listener to update the window height depending on the current size of the window (including window resize events). I then subtract this height by 80, compose a string for tailwind and update the className. While it works fine and the inspector shows it is dynamically updating the div’s height visually is not adjusting as it should be.

New Attempt with window event listener and calculation. Note the calcualted heightMinusNavbar is correctly updated when resizing the window but visually will not

import React from "react";
import Gallery from "../components/gallery/Gallery";
import Navbar from "../components/navbars/Dapp";

class dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = { width: 0, height: 0 };
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
  }

  componentDidMount() {
    this.updateWindowDimensions();
    window.addEventListener("resize", this.updateWindowDimensions);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.updateWindowDimensions);
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight });
  }

  // todo: change height to be full screen subtracted by nav height

  render() {
    const heightMinusNavbar = `h-[${(this.state.height - 80).toString()}px]`;
    console.log("heightMinusNavbar " + heightMinusNavbar);

    return (
      <>
        <Navbar />
        <div
          className={`w-screen text-gray-300 y-full bg-gray-900 ${heightMinusNavbar}`}
        >
          <Gallery />
        </div>
      </>
    );
  }
}

export default dashboard;

What am I doing incorrectly?

Advertisement

Answer

If your navbar is a fixed height of 80px, you could just use an inline calc class.

<div class="h-20 bg-slate-300">Navbar</div>
<div class="h-[calc(100vh-80px)] bg-slate-100">Gallery</div>

https://play.tailwindcss.com/bOun5kbE3O

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement