Embed a function within styled-components that triggers on window.onload

Currently, I'm working on a sidebar that doesn't have its full height. My goal is to calculate the difference between the height of the header and the height of the window screen.

const setSidebarHeight = () => {
    return (window.onload = () => {
        if (document.getElementById('navigation-bar')) {
            return ( window.innerHeight - document.getElementById('navigation-bar').clientHeight );
        }
    });
}

const SideBarDiv = styled.div`
    color: #232323;
    background-color: #f4f3f4;
    float: left;
    position: relative;
    z-index: 100;
    height: ${setSidebarHeight()}px;
`;

I'm wondering how to appropriately use window.onload to dynamically adjust the height attribute in CSS. The current code does not display any pixel values in the browser developer tools.

If anyone has insight on this issue, I would greatly appreciate your help. Thank you!

Answer №1

Utilizing CSS#calc, you have the ability to calculate dynamic heights.

Employ the viewport height.

height: calc(100vh - 20px) // Where 20px is the height of the header

Answer №2

I may not fully grasp your query, however, I do have a solution in mind

const adjustSidebarHeight = () => {
 return (window.onload = () => {
  if (document.getElementById('navigation-bar')) {
   return ( window.innerHeight - document.getElementById('navigation-bar').clientHeight );
  }
 });
};

render() {
  <StyledSideBar height={this.adjustSidebarHeight()} />
}

const StyledSideBar = styled.div`
 // ....
 height: ${props => props.height}px;
`;

Answer №3

Although RIYAJ KHAN provided a solid answer, I'd like to offer an alternative approach to your original question.

The solution involves defining a variable within the onLoad method and using it in your component string.

var panelHeight = 0;
window.onload = () => {
        if (document.getElementById('navigation-bar')) {
             panelHeight = window.innerHeight - document.getElementById('navigation-bar').clientHeight ;
        }
}

Next...

const SideBarDiv = styled.div`
    color: #232323;
    background-color: #f4f3f4;
    float: left;
    position: relative;
    z-index: 100;
    height: ${panelHeight}px;
`;

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

Using Protractor to scroll down within a dialog container in order to click on an element

Seeking to interact with hidden elements using protractor within a Dialog Container (See Image of Dialog Container). Despite trying various options, I have not been successful so far. (tests in chrome) My Configuration: I/status - selenium standalone vers ...

I can't believe this ReactJs project generated this code automatically

What does this automatically generated code do in my ReactJs app and what are the advantages of including it? <div class="nsc-panel nsc-panel-compact nsc-hide"> <div class="nsc-panel-move"></div> <div class=" ...

What is the best way to assign a data attribute value based on an element's index using jQuery?

I am dealing with multiple sibling elements that are added dynamically or manually using JS. Each element has a data attribute called "data-sec_number" with a number value that increments by one for each subsequent element down the page. Currently, I am ma ...

Tips on utilizing the b-pagination API?

layoutchange() { this.layout = !this.layout; if (this.layout === true) { this.perPage = this.layout ? 8 : 12; this.listProducts(); } else { this.perPage = !this.layout ? 12 : 8; this.gridProducts(); } }, <a class="list-icon" ...

Using express.js to retrieve a JSON file via the command line

In need of assistance on how to retrieve a JSON file using express.js. My goal is to access it through the Mac terminal for a college assignment that involves creating an HTTP server acting as a basic data store. The requirements include responding to GET, ...

Tips for Saving JWT Token for Server-Side Rendering in Next.js 14 Without Relying on localStorage

Currently, I am encountering a challenge with storing a JWT token in Next.js 14. My goal is to load a page using SSR, but the use of localStorage is not possible in server-side components. Here's my situation: upon logging in, the backend provides a J ...

Utilizing async/await functionality within a React-Native component

I'm currently working on implementing a feature that authenticates users before rendering the main 'App' component. However, I'm facing an issue where my code is executing before the promise is resolved. class App extends Component { ...

Ensure input integrity within Node.js/Express server before transferring outcome to React client-side

Checking the validity of a domain entered by a user in my React front-end is crucial. The process involves sending the domain to my Nodejs/Express back-end and utilizing the Node function dns.lookup for validation. app.post('/new-cert', function ...

Recreating the MUI v5 Popper scrolling feature in a CodeSandbox playground

I'm trying to locate the reference code for MUI v5 Popper scroll playground in order to address some issues I'm experiencing with the dynamic arrow within the popper. Unfortunately, the arrow is not behaving dynamically as expected. Click here ...

Best practices for utilizing Async/Await in Node 8: A comprehensive guide

With node version 8, async/await becomes available, making code linear for the first time in nodejs natively. This is a nice improvement. In the past, many articles claimed that functions with try/catch blocks were not optimized in the v8 javascript engi ...

NodeJS - Bluebird: implementing a loop with a waiting mechanism for completion

Struggling with a seemingly simple task in my NodeJS and MongoDB project. I've included Bluebird for promises, but need some help. In my code, I have a basic for-loop that generates random names and pushes them into an array: const PlayerGenerator = ...

Issue with Cloud Code function preventing data from being saved

After successfully testing this code in Angular and getting the correct responses in console.log, I decided to migrate it to cloud code. Since the function manipulates data in the user table, I had to use the master key and implement it in cloud code. Howe ...

Show text with condensed lines in CSS without breaking words

Within this div, I have a long text that needs to be displayed on multiple lines based on the fixed width and height of the div. The challenge is to ensure that words do not break in the middle when moving to the next line, and also add an ellipsis at the ...

Location of the search bar

I am having trouble figuring out which class in Bootstrap I should modify in order to center the search bar in the navigation bar. Can anyone help? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> ...

Animation will begin once the page has finished loading

On the website, there is a master page along with several content pages. The desired effect is to have a fade-in animation when navigating between pages. Currently, when clicking on a link, the new page appears first and then starts fading out, but this sh ...

When using Selenium to locate an element, it appears to be returning an unexpected empty object

This question has been bothering me for quite some time. I am currently using Selenium in conjunction with Python to find an element within a webpage. The specific element I am targeting is as follows: <a id="topmenu_adhocQtraditional_Reports" ...

The iOS browser fails to display the image requested via Ajax, even though it has been loaded into the DOM

Update: The issue with the image size does not seem to be the cause, as other photos on my website load without any problems. Upon further investigation, I discovered that this problem only occurs when browsing on iOS. It functions properly on Android de ...

Is it possible for an image to be displayed in another div or table column when I hover my mouse over it?

I am looking to create an image gallery with thumbnails on the left side. When I hover over a thumbnail, I want the full image to be displayed in another section on the page. Can anyone provide me with the correct code or suggest a plugin to achieve this f ...

Issues with functionality of drop-down menu

For some reason, when I hover over the menu item "support," the text doesn't show up in the drop-down menu. I've double-checked my CSS multiple times, but I can't seem to pinpoint where the issue lies. HTML Code <body> <div class= ...

Breaking apart web addresses and their attached parameters

I am attempting to extract the part of a URL that comes after the last forward slash (/) and before the querystring. While I have been successful in obtaining the last segment of the URL, I have encountered difficulty in removing the querystring from it. ...