Can you control the order of rendering for specific divs in a ReactJS application?

I need assistance with developing a mobile app using ReactJS and react bootstrap that can dynamically resize itself based on the screen size. One specific part of the app requires calculations to determine its dimensions based on the remaining space on the screen after other elements have been rendered.

Here is an example scenario:

var calcWidth = (100 / tableSize).toString() + '%';
return( 
<Container>
    <Row id='1'>Header and other static components here</Row>
    <Row id='2'>
        //A database-driven table with square shaped cells is included here, structured as follows -
        <Container style={{width:'100%'}}>
            <Row><Col style={{width:calcWidth, paddingBottom:calcWidth}}></Col>...</Row>
            ...
        </Container>
    </Row>
    <Row id='3'>Footer and other static components here</Row>
</Container>
);

In the code snippet above, Row 1 and Row 3 contain fixed content such as headers, footers, buttons, etc. Row 2 consists of a table with square cells that need to be centered both horizontally and vertically.

The current implementation calculates the width of each cell based on the container's width effectively creating square cells that fit perfectly horizontally. However, since the height matches the width, it causes the footer element to extend beyond the screen leading to scrollbars appearing. To avoid this issue, the width calculation should be adjusted based on the available height for the table, like so -

var remainingHeight = <total height of the container> - <height taken up by Row 1> - <height taken up by Row 3>
var width = <width of the screen>
var calcWidth = ((remainingHeight < width ? remainingHeight : width) / tableSize).toString() + '%';

My queries are as follows:

  1. How can I determine the value of the remainingHeight variable? Is there a way to ensure Row 1 and Row 3 render before calculating the remaining height for Row 2?
  2. What method can be used to ascertain the total height and width of the container?
  3. Are there any alternative approaches or CSS techniques that could simplify this process? As a beginner, I'm open to suggestions for more efficient solutions.

Answer №1

Check out this example showcasing how to dynamically calculate the height of React components:

https://i.stack.imgur.com/UgFiP.png

export default function App() {
  const [height1, setHeigt1] = useState(0);
  const [height2, setHeight2] = useState(0);
  const [height3, setHeight3] = useState(0);
  const [remainingHeight, setRemainingHeight] = useState(0);

  useEffect(() => {
    const remainingHeight = 100 - height1 - height2 - height3;
    console.log(remainingHeight);
    setRemainingHeight(remainingHeight);
  }, [setRemainingHeight, height1, height2, height3]);

  return (
    <div
      id="container"
      style={{
        height: "100px",
        backgroundColor: "firebrick",
        padding: "15px"
      }}
    >
      <ResizableComponent
        id="component-1"
        content={`Initial component 1 height = ${height1}`}
        onHeightUpdated={setHeigt1}
      />
      <ResizableComponent
        id="component-2"
        content={`Initial component 2 height = ${height2}`}
        onHeightUpdated={setHeight2}
      />
      <ResizableComponent
        id="component-3"
        content={`Initial component 3 height = ${height3}`}
        onHeightUpdated={setHeight3}
        remainingHeight={remainingHeight}
      />
    </div>
  );
}

export function ResizableComponent({
  id,
  content,
  onHeightUpdated,
  remainingHeight
}) {
  const [height, setHeight] = useState(0);
  const [isFirstRender, setIsFirstRender] = useState(true);

  useEffect(() => {
    const newHeight = document.getElementById(id).clientHeight;
    if (height !== newHeight && isFirstRender) {
      setHeight(newHeight);
      setIsFirstRender(false);
    }
  }, [isFirstRender, id, height, onHeightUpdated, remainingHeight]);

  useEffect(() => {
    onHeightUpdated(height);
  }, [height, onHeightUpdated]);

  return (
    <div
      id={id}
      style={
        remainingHeight
          ? {
              backgroundColor: "pink",
              height: `calc(${height}px + ${remainingHeight}px)`
            }
          : { backgroundColor: "pink" }
      }
    >
      {content}
    </div>
  );
}

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

Instructions on obtaining a distinct daily array from the weather API array that provides a detailed 5-day weather report every 3 hours

Seeking assistance with my weather app development on React using axios with the openweathermap.org API. Currently stuck on getting data formatted in a specific way from the 5-day forecast it provides, totaling 40 reports over the 5 days. The API response ...

Adjust link when scrolling through the webpage

I am looking to update the URL while scrolling instead of changing the menu class. Here's the reference I found: https://codepen.io/anon/pen/LdLgNo I made some modifications by adding push state, but I'm facing an issue with a fixed header. I ...

Generate a fresh line within the source code

Currently, I am facing a challenge with dynamically loading CSS, JS, and other components as it appears messy when viewed from the source. Although this issue does not impact functionality, I am not satisfied with how it looks in the source code. When exam ...

What is the best way to superimpose text on a variety of images with varying sizes using CSS

I have a client who is requesting a sold text to be displayed on top of all images that have been sold, positioned in the bottom left corner of each image. While I have successfully implemented this feature, the issue arises when dealing with images of var ...

react-Draggable DnD: Experience a beautiful way to effortlessly drag and drop items within a container, where the

I am currently using Beautiful DnD in my React Project and I have run into a bug. Only the last item in a droppable container is draggable. Whenever I try to click on other items, it shows me a warning saying "Unable to find draggable with id: id1". Howeve ...

The paragraph element is refusing to align with the next paragraph element on the following line

The issue I'm facing is that the paragraph element is not displaying on a separate line from the other paragraph element. body { margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; backgr ...

When an SVG image is embedded, its color may not change even after being converted to an inline SVG

I've inserted an SVG using an img tag. When hovering over it, I want the fill color of the SVG to change. I attempted to convert the SVG to inline SVG following this method, but it doesn't seem to be working as expected. No console errors are b ...

Is there a method to change the name of a file and have it automatically updated in all other locations where it is referenced?

I need to change the name of an HTML file within Visual Studio Code, but this file is referenced in multiple other files. Is there a quick way to do this? Are there any shortcuts that will let me rename the file and automatically update all references in ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Move the DIV element to a static section within the DOM

In my Vue app, I have implemented methods to dynamically move a DIV called 'toolbox' to different sections of the DOM. Currently, the DIV is positioned on the bottom right of the screen and remains static even when scrolling. My goal is to use t ...

Leverage URL parameters as a prop within a React component

I am grappling with setting up an onLoad event in order to retrieve data from my database. My challenge lies in utilizing a URL parameter as a prop for this task, and I seem to be stuck on how to access it. Currently, I am working with react-router v6, ev ...

We were unable to identify any Next.js version in your project. Please ensure that the `"next"` package is installed in either the "dependencies" or "devDependencies" section

My attempt to deploy a Next app using the Vercel CLI has hit a roadblock. After running vercel build with no errors, I proceeded to deploy with vercel deploy --prebuilt, which also went smoothly. However, when trying to move the project from the preview en ...

Accessing the host in NextJS using _document.js or _app.js

I am currently working on a NextJs website that operates on various hostnames. Upon the application's initialization, I need to fetch data from an API based on the specific URL where NextJS is deployed. For instance, if my NextJS is running on websit ...

Forming triangles with outlines

Recently, I had the challenge of designing speech bubbles and found a clever technique to create the triangular tip at the end using CSS. By setting the element's width and height to 0 and playing around with borders, you can achieve diagonal shapes f ...

Setting initial opacity for CSS on page load

I'm not a pro at web design, but I'm trying to create my own website. I've divided my page into two sections - the left side for the menu bar and the right side for content. To add a 'cool' blur effect over my menu bar, I decided t ...

Guide on setting up Material UI with the latest experimental `app/` directory in Next.js

The documentation offers a sample here for material-next-ts. Unfortunately, I was unable to set this up in the recently introduced experimental app/ directory. Can anyone clarify what is the corresponding file for _app.ts or _document.ts in the new app/ ...

Utilizing React.hydrate in conjunction with Vue: A Beginner's Guide

Wondering about a unique scenario here - I have a website built with Vue and now I aim to showcase a library I developed in React. In order to steer clear of server-side rendering (SSR), I can simply wrap ReactDOM.hydrate(ReactApp, document.getElementById( ...

What is the most effective method for structuring JSON data that is utilized by a single-page application (SPA)?

A colleague and I are collaborating on a single page application (built in React, but the framework used isn't crucial; the same query applies to Angular as well). We have a database with 2 interconnected tables: Feature Car Both tables are linked ...

Is there a combination of 'auto' and 'none' values in any CSS properties?

Is it safe to assume that if a property is set to auto, it cannot have the value of none, and vice versa? Or if a property has none, can it not have auto as well? I understand that these values have distinct meanings, but I am curious if this concept has ...

The hierarchy of CSS in Vue components

I've developed a customized CSS framework to streamline the design process across all my internal projects. The central file is structured as shown below: @import "~normalize.css/normalize.css"; @import "_variables.scss"; @import "_mixins.scss" ...