Modify flex direction to column in response to changes in height of another div or when its content wraps

I am currently utilizing React MUI V5 and I am looking to modify the flex direction of a div from row to column when a preceding div changes in height or wraps.

Below is a basic example of what I have implemented using plain HTML/CSS, but I am uncertain if there is an alternative method with flexbox to achieve this:

      .parent{
        display:flex;
        flex-direction: row;
        flex-wrap: wrap;
      }
      .child1{
        display: flex;
        max-width: 80%;
        padding: 10px;
      }
      .child2{
        display: flex;
        max-width: 80%;
        height: 30px;
        flex-direction: row;
      }


    <div class="parent">
      <div class="child1">
<p>
      so much data here. so much data here so much data here so much data hereso much data here v so much data here v so much data here vso
      so much data here. so much data here so much data here so much data hereso much data here v so much data here v so much data here vso
      so much data here. so much data here so much data here so much data hereso much data here v so much data here v so much data here vso
      so much data here. so much data here so much data here so much data hereso much data here v so much data here v so much data here vso
   </p>
    
      </div>
      <div class="child2">
        <button>Button1</button>
        <button>Button2</button>
      </div>
    </div>

A jsFiddle version can be found here showcasing the above setup.

In essence, if the child1 class div remains as a single line without any wrapping or height adjustment, then the flex-direction: row should be maintained for the child2 class. However, it needs to switch to flex-direction: column when the child1 class wraps its content or experiences any change in height.

I am unsure of how to implement this within my MUI component and whether MUI V5 breakpoints could be utilized?

In the jsFiddle example provided, the flex-direction should transition to column once the contents of the child1 div have wrapped.

Answer №1

The React or MUI libraries are not visible in the provided code snippet.
To incorporate a state for the current height of the first child, it is essential.
By utilizing a 'ref' for the first child, we can continuously update the 'height' within the `useLayoutEffect` during each render to ensure the most recent div height.
Furthermore, I've incorporated MUI 'sx props' for styling purposes.

import { Box } from "@mui/material";
import React, { useLayoutEffect, useRef, useState } from "react";

export default function test() {
  const [height, setHeight] = useState(0);
  const ref = useRef(null);

  useLayoutEffect(() => {
    setHeight(ref.current.clientHeight);
  });

  return (
    <Box sx={{ display: "flex", flexDirection: "row", flexWrap: "wrap" }}>
      <Box
        sx={{
          display: "flex",
          maxWidth: "80%",
          padding: "10px",
        }}
        ref={ref}
      >
        <p>
          Lots of data here.
        </p>
      </Box>
      <Box
        sx={{
          display: "flex",
          maxWidth: "80%",
          flexDirection: height < 45 ? "row" : "column",
        }}
      >
        <button>Button1</button>
        <button>Button2</button>
      </Box>
    </Box>
  );
}

Answer №2

It is impossible to achieve this using only CSS or MUI V5

  • To accomplish this, you will need to utilize media queries or JavaScript

By employing JavaScript, when items are wrapped, the element's offsetHeight surpasses the baseHeight value of 0 and then alters the flex direction accordingly.

function detectWrap(id) {
    let element = document.getElementById(id);
    // Base height threshold set at 178
    return (element.offsetHeight > 178);
}

window.onresize = function (event) {
   detectWrap("child1");
}

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

Encountering an issue with NextJS 13 when utilizing the vectorstore recommended by Langchain, specifically receiving an error message stating that HNSWLib

Currently, I am building an application utilizing Langchain and OpenAI for assistance. My approach involves loading data using JSONLoader and intending to save it in a vectorstore. This way, I can provide specific answers to user queries based on the store ...

Position a grid item in the center

Can someone help me with centering my container's item? I am struggling to align the third item to the center using display: grid. Previously, I attempted to use flexbox but found it to be less effective for a responsive layout. .projetos { f ...

Syncing OrbitControls rotation with camera rotation for improved navigation

Currently utilizing @react-three/fiber to incorporate first person controls (WASD & cursor keys) along with OrbitControls for scene navigation. Mirroring PointerLockControls, I've successfully implemented the WASD controls by updating the target vecto ...

Choose only ul elements up to a specific level of depth

ul, ul ul, ul ul ul { list-style: none; margin: 0; padding: 0; } Inquiry: Is there a specific selector that I can utilize to apply styles to every nth level of ul? For instance: ul > ul ...

What is the best way to retrieve data from the server using (Express) after the form data has been submitted (React) and successfully processed?

I am in the process of developing a search-based web application for League of Legends, a popular MOBA game. This app allows users to input their summoner's name and retrieve general information using the game's third-party API. While I have suc ...

Is it feasible to display Material components inside a material-table?

Currently, I am in the process of developing a data display feature for my application and have been exploring various data table components that are constructed using Material UI. One question that has arisen is whether it is feasible to incorporate Mater ...

The "hidden" class in Bootstrap 4 is not functioning as expected

I have Bootstrap v4 set up with its default CSS and JS. I'm attempting to use the classes hidden, hidden-XX-down, and hidden-XX-up on different divs, buttons, etc. However, it doesn't seem to be having any effect. All other classes are working fi ...

What is the best way to receive a callback when a user cancels a dialog box to choose a mobile app after clicking on

I am currently exploring HTML coding for mobile devices and looking to integrate map routing functionality. When it comes to mobile devices, utilizing the local app is the more practical option, and I have had success implementing this by modifying the l ...

I'm curious as to why my form fields disappear even when they have not been selected

Illustration of Form Fields Disappearing When Unselected Greetings, I'm encountering an issue where my form fields disappear when not selected. I'm utilizing Crispy Forms to render the form, following a tutorial on YouTube. This functionality w ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...

Encountered Error : Uncaught Rejection (SyntaxError): JSON data ended unexpectedly

I'm facing a challenge with fetching in React as I attempt to connect my Node API running on port 8000. Everything was working smoothly initially until I introduced a fetch for another function, resulting in the following error message: const API_URL ...

Is it possible to refresh a table that is currently displayed in a model popup?

My code to reload a table or div inside a model popup continuously is not working as expected. Can you help me with this issue? I attempted to utilize ajax for this purpose but unfortunately, the code below is not updating chats (I am working on a chat ta ...

Using just a simple HTML code, the d-flex feature in Bootstrap seems to be malfunctioning

Embarking on a new Bootstrap website project has presented me with a challenge that I have not been able to overcome, even with minimal HTML and just one flex item (which happens to be the only element on the site): <!DOCTYPE html> <html lang=" ...

What is the best way to implement pushstate degradation – using backbone.history or history.js?

I am interested in implementing pushstate functionality, which involves making an ajax request, changing the URL, and adjusting the browser history stack. However, since pushstate is not universally supported by all browsers, I need to find a workaround f ...

"The re-rendering of a component is not triggered correctly when using React hooks setState

I am working with a component called toggle Menu List that is supposed to load a child component (toggle Menu Items) on button click. Here's how it's supposed to work: The initial state of 'btnId' is set to null. -> When the butto ...

"Unleashing the power of ReactJS in an endless

When I receive props from a child component in the getCount function and set it as a prop into state, I encounter an infinite loop when trying to set it in the component. How can I resolve this issue? Here is the code for the parent component: import R ...

How can I effectively organize REST backend API requests when using React?

As my colleagues and I collaborate on developing a full stack web application, we have chosen React as our frontend framework. Our project involves performing CRUD operations on multiple resources, which means creating various pages. In the past, I came a ...

What is the best way to position a div below a sticky navbar?

I have implemented a sticky navbar on my index page along with JavaScript code that adjusts the navbar position based on screen height. When scrolling, the navbar sticks to the top of the page, but the flipping cube overlaps with the sticky navbar. How can ...

"Looking to log in with NextAuth's Google Login but can't find the Client Secret

I am attempting to create a login feature using Next Auth. All the necessary access data has been provided in a .env.local file. Below are the details: GOOGLE_CLIENT_ID=[this information should remain private].apps.googleusercontent.com GOOGLE_CLIENT_SECR ...

Copying to the clipboard now includes the parent of the targeted element

Edit - More Information: Here is a simplified version of the sandbox: https://codesandbox.io/s/stupefied-leftpad-k6eek Check out the demo here: https://i.sstatic.net/2XHu1.jpg The issue does not seem to occur in Firefox, but it does in Chrome and other ...