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

Sketch a variety of numerical values in a circular formation

I was working on a number circle using the below fiddle, but I need it to always start from 0 at the top. How can I achieve this? Additionally, I would like to connect the numbers from the inner circle border to the number with a dotted line. How can I dr ...

After modifying the template, the ReactDOM.render() function fails to work when called again

Initially, the render() function works perfectly. However, upon calling it again through one of the event handler functions, it fails to work. The Chrome DevTools console does not show any errors. The changes are made within the options array and then nee ...

Spreading an object to remove a key may result in the returned value being

When creating a Radio Button object, each object in the array consists of {value: 1, text: 'Sometext'}. If a radio button is selected, 'selected: true' is added to that specific object and removed from the others. const onChoiceChange ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

incapable of destructuring two objects simultaneously

Is there a way to map movies using columns as a property reference? For example: {movies.map(item => {columns.map(column => item.column.path)})} When I try this, the result is always undefined. The 'movies' array contains detailed inform ...

Using the power of Selenium's XPath, we can easily navigate through a table to access

Looking for assistance in creating selenium xpath for the various column links within a table. Each row has a unique identifier and contains information about a product, including the name. Based on the product name, I need to locate other links within the ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

encountering an issue following the initial setup using create-next-app

After searching on Stack Overflow and finding no answers, I am posting this question again. When I create a new project in Next.js using npx create-next-app project-name --ts and run npm run dev without making any changes to the source code, I encounter t ...

Is it possible to remove the left margin on an li element by placing a td element inside it using HTML and

Here is my custom HTML code including the CSS styles: <!DOCTYPE html> <html> <head> <style> table td { border: 1px solid black; } li { margin-left: 3 ...

Looking for an explanation for the mysterious code in the Button Component MUI - can anyone shed some

Here we have some code from Material UI that can be found on GitHub's MUI on line 13. Once Babel 2016 compiles this code, it transforms into: (0, _extends2.default)({}, theme.typography.button, ...) What is this syntax? Has anyone seen this before? ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

Exploring TypeScript implementation of Redux toolkit's store

I'm currently diving into the world of Redux in React + TypeScript by following the tutorials provided by Redux Toolkit. I am attempting to implement it in a sample application. My main struggle lies with typings related to the store and the mappStat ...

Alpinejs Mega Menu Issue: Hover Functionality Glitchy

I'm working on a complex Mega Menu project that is activated upon hovering, using the powerful combination of Tailwind CSS and Alpinejs. The functionality is mostly there, but I've encountered some bugs along the way. Despite my attempts to impl ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Configuration options for Path Aliases in TypeScript

In my Next.js project, I am utilizing TypeScript and have organized my files as follows: |-- tsconfig.json |-- components/ |---- Footer/ |------ Footer.tsx |------ Footer.module.sass My path aliases are defined as:     "paths": {       ...

Issue with big-react-calendar: 'momentLocalizer' property is not defined

I encountered an issue while trying to execute the sample code for the react-big-calendar component. The error message reads as follows: Uncaught TypeError: Cannot read property 'momentLocalizer' of undefined Below is the snippet of the code: i ...

Turn off hover opacity effect for a specific image

Currently, I've implemented a hover opacity effect on my images using the following CSS: img { opacity: 1.0; filter: alpha(opacity=1.0); } img:hover { opacity: 0.6; filter: alpha(opacity=0.6); } However, I now have a specific image for whi ...

Adjust the size of a textarea once text is removed

When you type text, a textarea expands in size. But what if you want it to dynamically decrease its height when deleting text? $('textarea').on('input', function() { var scrollHeight = parseInt($(this).prop('scrollHeight&apos ...

Using Jquery to set up an event listener on a child div that changes the CSS property of its parent div

I am currently working on a product customization form where the radio buttons are hidden using opacity:0. My goal is to have the border of the image turn black when an option is selected as a visual feedback for the user. I've implemented an event l ...

Rendering React.js components as children of DOM elements

Trying my hand at creating a custom Map component includes the task of designing a unique Map Annotation. Here's an example of how a MapAnnotation component appears in the render function: <MapAnnotation title='Annotation' latitude={ 12.3 ...