Home > Software engineering >  How to adjust the component height with browser height?
How to adjust the component height with browser height?

Time:04-01

Background

I try to match the height of the component with the height of the browser.

There are three images in the component, and the component height is more than the browser height.

So, I made this code to match them.

function Container({ children }: Props) {
  const [maxWidth, setMaxWidth] = useState<string>('100%');
  useEffect(() => {
    const $app = document.querySelector('#root') as HTMLElement;
    const $body = document.querySelector('body') as HTMLElement;
    if (!$app || !$body) return;
    const _maxWidth = Math.floor(
      ($body.clientHeight / $app.offsetHeight) * $app.clientWidth,
    );
    setMaxWidth(`${_maxWidth}px`);
  }, []);
  return (
    <div className="container pt-10 pb-10" style={{ maxWidth }}>
      {children}
    </div>
  );
}

export default Container;

Problem

However, the width of the component often applies differently than expected. I think the height was not calculated properly because there was a time for the image to be loaded. What should I do in this case?

  1. recalculate the width of the component after the image is loaded
  2. whenever there is a change in the height of the component (MutationObserver?), the component's width should be recalculated.

That's all I can think of now.

Do you have any better ideas?

CodePudding user response:

You can get the window height and width by this:

const { innerWidth: width, innerHeight: height } = window;

Check this Here.

CodePudding user response:

I dont think you have to do this to accomplish what you want..

If your goal is to fit your Container dimensions with the window dimensions, you should consider using vw and vh units.

Then you can set your images dimensions according to the parent with css only. They are several way to do this, depending on your final template.

What about something like:

container {
  display: flex;
  flex-direction: row;
  align-items: center;
}

EDIT:

Care with viewport units cause these units are not relative to your parents and could cause unwanted behaviors. An other way is to set all you parents at 100%.

Take a look to this example:

  • Related