Is there a way to determine the app bar height within a React Material UI application?

I'm trying to create a full-screen image for the opening of my website using React and Material UI. Here's a snippet of my JSX code with the default Material UI theme:

<AppBar>
//code in between 
</AppBar>

<Container sx={{margin: '0px', padding: '0px'}}>
   <img src={headerPicture} style={{minHeight: '100vh', maxWidth: '100vw'}}/>
</Container>

The problem is that 100vh doesn't consider the height of the app bar, making the image and app bar larger than the screen. To address this issue, I think I need to adjust the image styling like so:

<img src={headerPicture} style={{minHeight: '100vh - AppBarHeight', maxWidth: '100vw'}}/>

How can I determine the height of the app bar dynamically as it resizes?

Answer №1

In one of my projects, I implemented a solution where I set a fixed height for the AppBar and used constants to manage its responsiveness.

  • Here is an example of how it was done in AppBar.js:
export const APP_BAR_HEIGHT = 80;
export const APP_BAR_HEIGHT_LG = 140;

const AppBar = () => {
    return (
        <div style={{ height: isLargeScreen ? APP_BAR_HEIGHT_LG : APP_BAR_HEIGHT}}>
            {/* app bar content here */}
        </div>
    );
}
export default AppBar;

After defining these constants, they were imported and utilized throughout the project.

Further Improvement:

I also created a custom hook to manage window height changes more effectively.

const useWindowHeight = () => {

    const [height, setHeight] = React.useState(window.innerHeight);
    React.useEffect(() => {
        const handleResize = () => {
            setHeight(window.innerHeight);
        }
        window.addEventListener('resize', handleResize);
        return () => {
            window.removeEventListener('resize', handleResize);
        }
    }, []);
    return height;
}

This custom hook helped in ensuring accurate height calculations, especially on mobile devices with changing window heights during scrolling. Ultimately, the implementation would look something like this:

import AppBar, { APP_BAR_HEIGHT, APP_BAR_HEIGHT_LG } from 'whateverpath';

// ...
const windowHeight = useWindowHeight();
return (
    <>
        <AppBar>
             //additional code goes here
        </AppBar>

        <Container sx={{margin: '0px', padding: '0px'}}>
            <img src={headerPicture} style={{minHeight: windowHeight - APP_BAR_HEIGHT, maxWidth: '100vw'}}/>
        </Container>
    </>
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on defining the specific CSS and JavaScript code to include in your Flask application

I am currently working on a web application using Flask and I need to specify which CSS and JS files should be included in the rendered HTML page based on a condition. There are times when I want to include mycss1.css and myjs1.js: <link href="/sta ...

Enabling CSRF protection between a ReactJS frontend and a Spring Boot backend across different domains

Our setup includes a frontend React JS application and a backend Spring Boot API with CSRF enabled, running on different domains. What is the most effective approach for passing the CSRF token between the REST API and the React application? ...

Error message: Angular JS encountered an issue when trying to initiate the test module. The cause

When I run JavaScript within an HTML file and use AngularJS with ng-repeat function, I encounter this console error: angular.js:38 Uncaught Error: [$injector:modulerr] Clicking on the link in the error message leads to: Failed to instantiate module test ...

React state is cleared as an empty string when a 'number' type input is used

My input component is causing issues <input value={this.state.age} onChange={e=> {this.setState({age:e.target.value})}} type='number' /> Everything works as expected when only numbers are entered. However, if a minus sign, plus sign, ...

Incorporating a javascript library or plugin into Vue.js code

Hey there, I recently came across the really cool component called vue-social-sharing. It's my first time using a library like this and I'm a bit confused on how to set it up properly. I've installed it through NPM, but when it comes to the ...

add a border to an image when it is hovered over

I'm having trouble getting the hover effect to work on my images. I suspect that I may be targeting the CSS hover incorrectly, and there could also be a conflict with the jQuery code that is attached to the images. Here is the link to the fiddle: ht ...

How can I switch between columns in a dual-column layout?

In my latest project, I utilized CSS Flexbox to create a sophisticated two-column layout that allows toggling each column independently. While this functionality is exactly what I need, I can't help but feel that my current method is somewhat cumberso ...

The footer at the bottom of the page is currently malfunctioning

I was able to create an always on the bottom footer using code from Codepen. Here is the HTML: <div class="content"> <header> <p>blabla</p> </header> <main> <p>blaBlabla blub</p ...

Using float instead of CSS inline-block is more effective for styling a PHP element

I've been working on styling a page that was generated with App Gini. While I have been successful in editing most elements so far, I am facing an issue with getting inline-block to work properly. Although float:left is functioning correctly, I would ...

Tips for retrieving specific data from a variable in an object using PHP

I am facing a challenge in accessing the value of an object with an array in PHP Laravel. Currently, I have successfully accessed the information using the following method. However, the issue arises when the position of the required information changes, f ...

How can I center an image next to text on two lines, that is compatible with IE7?

I am trying to align an image (logo) with text in two lines - the website title and a brief description. Here is my attempt using HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional ...

I'm looking for a way to convert an array value to JSON using jQuery

i need assistance in converting an array value into json format. An example is provided below: Sample Array [Management Portal!@!@Production Issue Handling!@!@/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!@!@ Event Browser!@!@/ION ...

Align the button at the center of the carousel

While working on a personal HTML/CSS/Bootstrap 5 project as a self-taught learner, I have encountered some beginner doubts. My challenge is to ensure that the site remains responsive across various devices such as mobile and tablet. Specifically, I am stru ...

What does the term "xs" signify in relation to Grid layout

Can you explain the significance of the xs in this code snippet? <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> < ...

Unleashing the Power of Lodash Debounce in Vue

Currently, I have integrated debounce from lodash into my main.js file. import lodash from 'lodash' Vue.prototype._ = lodash I've been utilizing it like this._.find(...), and everything has been functioning smoothly. However, when attemptin ...

Implement ng-model on an input field that is pre-filled with a value from a different model within the Angular

One challenge I am facing involves pre-populating an input field with user information, such as their email address or first name, if that data is available. Initially, I set the value of the input field using $scope.userData. However, when I add an ng-mo ...

React Router Fails to Display Routes on Horizon

Exploring the world of web design, I decided to create a simple web app using Horizon and React. However, I encountered an issue with my Router not properly routing to subdirectories. When I try to access localhost:8181/Home, instead of displaying the expe ...

Using ReactJs Component to interact with Laravel Api and retrieve uploaded images

I need assistance retrieving my list from the Laravel API. I have successfully fetched the list details, but I am encountering difficulties fetching details with images. My card.js component import React, {useState, useEffect} from 'react'; imp ...

Error: The object #<HTMLCollection> does not support the 'tags' method

While trying to troubleshoot this issue, it seems like I haven't been able to pinpoint the simple solution. This particular javascript menu works perfectly in IE, however in Chrome, there is an error when trying to open the menu with a first-level cli ...

Rendering props conditionally in React

I am currently facing an issue with two different states retrieved from API calls: 'movieList' and 'search'. Both of them contain arrays of movies. The 'movieList' state is automatically rendered on the page to display popular ...