Achieving Flexbox compatibility with child elements in a horizontal MUI Collapse Component and TransitionGroup transitions: A comprehensive guide

Struggling with incorporating the Collapse + TransitionGroup Component in MUI while trying to make the containers expand using flexbox.

<Box sx={{display: 'flex', height: '100vh', width: '100vw'}}>
  <Box sx={{flex: 1}}>Content-A</Box>
  <Box sx={{flex: 1}}>Content-B</Box>
</Box>

Here is a basic setup I'm aiming for. Both Boxes side by side, dividing the entire page into left and right sections. However, integrating the Collapse Component causes issues:

<TransitionGroup sx={{display: 'flex', height: '100vh', width: '100vw}}>
  <Collapse orientation='horizontal'>
    <Box sx={{flex: 1}}>Content-A</Box>
  </Collapse>
  <Collapse orientation='horizontal'>
    <Box sx={{flex: 1}}>Content-B</Box>
  </Collapse>
</TransitionGroup>

The Collapse component seems to disrupt the Flexbox parent-child connection. Upon inspecting the DOM, I see that the Collapse Component adds 3 wrappers around the child component (root, outer, inner wrap). How can I pass down the flexbox properties to the original child?
I attempted to override the styles of these wrapping components in the theme and assign them display: flex, flex: 1 to propagate it all the way down to the child, but this results in choppy transitions.

EDIT: To clarify, the reason for needing the transition group is because I want a specific transition effect. Essentially, I have the page split into left (A) and right (B). When triggered, (A) should transition off the screen to the left (horizontally), (B) moves to where (A) was, and a new element (C) slides in from the right to take B's place. Think of it as a Sliding Queue. This process repeats (B exits -> C moves to B's position -> D transitions in). The problem arises when using Collapse horizontally as it doesn't adjust to fill the remaining space.

Answer №1

In my opinion, using css properties like flex and the Collapse component in this particular way may not yield the desired result. The Collapse component inherently applies css properties such as width: 0px, which might be overridden by your display:flex declaration.

Consider Using CSSTransition Instead

As an alternative approach, you can manually define and apply transition rules by utilizing the CSSTransition component, which is internally used by Collapse as well.

For more information, refer to the official documentation.

Here's an Example

You can find a sample scenario in this sandbox example

const useStyles = makeStyles({
  "slide-enter": {
    flexGrow: 0,
    width: 0,
    overflow: "hidden",
    whiteSpace: "nowrap",
    transition: "all 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms"
  },
  // Add more style definitions here
});

.......
     <TransitionGroup style={{ display: "flex" }}>
        {columns.map((_, i) =>
          i >= columns.length - 2 ? (
            <CSSTransition
              key={i}
              timeout={300}
              classNames={{
                appear: classes["slide-enter"],
                // Include other classnames
              }}
            >
              <ColoredBox>Content-{i}</ColoredBox>
            </CSSTransition>
          ) : null
        )}
      </TransitionGroup>

Past Answer for Reference

Previously suggested solution before receiving clarification from OP:
It seems a bit unclear what specific outcome you are aiming for.

Reason Behind Using Transition Group?

The purpose of including a TransistionGroup component is typically to automatically manage the 'in' property of a Collapse component when dealing with multiple items like adding them to a list.

If your intention is simply to render two columns without complex animations, you may omit the TransitionGroup and control the 'in' boolean manually.

Customizing Collapse Styling

To customize the styling of the collapse element, you can pass inline styles with required CSS properties. Example:

       <Collapse
          in={isOn}
          orientation="horizontal"
          style={{ flex: "1", display: "inline-block" }}
        >

A Demonstrative Example

Check out this detailed CodeSandbox demo

The demo showcases two versions:

  • Version 1 focuses on toggling between opening and closing columns
  • Version 2 involves dynamically adding columns and expanding them using TransitionGroup

Based on your query, it appears that Version 1 aligns better with your requirements:

const Example1 = () => {
  const [isOn, setIsOn] = React.useState(false);

  const toggle = () => {
    setIsOn((prev) => !prev);
  };

  return (
    <>
      <Button variant="contained" onClick={toggle}>
        {isOn ? "collapse" : "expand"}
      </Button>

      <Box display="flex">
        <Collapse
          in={isOn}
          orientation="horizontal"
          style={{ flex: "1", display: "inline-block" }}
        >
          <Box>Content-A</Box>
        </Collapse>
        <Collapse
          in={isOn}
          orientation="horizontal"
          style={{ flex: "1", display: "inline-block" }}
        >
          <Box>Content-B</Box>
        </Collapse>
      </Box>
    </>
  );
};

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

Is it acceptable to generate a standard redux update action?

What is the best approach and why? Consider there may be additional fields in addition to title and priority. Approach A: Implementing separate actions for each change: const todoReducer = (state, action) { switch (action.type) { case 'CHANGE_ ...

Can you tell me the standard font size in Internet Explorer 9?

After examining this particular website, I found the default styling used by IE 9. The body selector in particular appears as follows: body { display: block; margin: 8px; zoom: 1; } I would have expected a font-size declaration in this code, but su ...

I am experiencing issues with the Bootstrap responsive menu not functioning correctly on my template

While working on this Bootstrap 3 template, I observed that the default responsive menu is not functioning properly when I resize my browser for testing. I have previous experience designing responsive templates that work well, but this particular templat ...

Manual mocking in Jest is only effective for the initial function call

In my project, I have created a custom XHR wrapper in utils/xhr.js and I am using Jest manual mocking feature to mock it. However, I am running into an issue where only the first XHR call is being tracked: utils/xhr.js let xhr = { get: function(par ...

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

Tips on stopping slideToggle from opening and closing when clicked for the first time

When using the slideToggle function, I'm encountering an issue where the content div briefly shows on the first click but then immediately slides closed. Subsequent clicks work as expected and slide open correctly. This is the Jquery script I have be ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

Image element for Material UI CardMedia

There is a component in Material UI called CardMedia that allows for media content within a Card. The Mui website showcases an example using the img tag with CardMedia. https://mui.com/material-ui/react-card/#complex-interaction I am interested in using ...

Centering a button within a table-cell through movement

I'm facing an issue with aligning a button placed inside a table cell. The table setup is as follows: <b-table v-if="rows.length" :thead-tr-class="'bug-report-thead'" :tbody-tr-class="'bug-report-tbody& ...

Displaying the product price in a component header in Next.js when clicking on the product

I am relatively new to Next.js (React) and facing a challenge. I have created two components, header.tsx and product.tsx. These are being called in the file stepperLine.tsx under the "components" folder. My goal is to display the price of the product in th ...

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

Utilizing ReactJS material-UI to extract information from nested JSON in a table format

My application uses ReactJS on the client side and Java Jersey on the server side. The Java Jersey backend produces JSON data with nested structures as shown below: [ { "projectname": "BMI", "testRun": &qu ...

What is the process for assigning a custom React component as the Type for a prop in another component?

Currently, I am working on a customized GenericModal component and would like to include an array of my ModalText components as props in the GenericModal for display purposes. I want to specifically define the type of prop being passed, rather than using s ...

Clicking will cause my background content to blur

Is there a way to implement a menu button that, when clicked, reveals a menu with blurred content in the background? And when clicked again, the content returns to normal? Here's the current HTML structure: <div class="menu"> <div class=" ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

What is preventing my video from filling the entire screen?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=d ...

Jquery bypasses original stylesheet settings when inline styles are removed

I have a CSS file with various styles defined within it. One style in particular has the property position set to 'fixed', but this only applies to specific combinations of classes. For example: .mystyle.blue { position: fixed; } Here, el ...

Injecting CSS styles into dynamically inserted DOM elements

Utilizing Javascript, I am injecting several DOM elements into the page. Currently, I can successfully inject a single DOM element and apply CSS styling to it: var $e = $('<div id="header"></div>'); $('body').append($e); $ ...

CSS - borders are overlapping with one another

Encountering an issue where the bottom border is overlapping the right border on the same element. Here's a visual representation of the problem: The green right border's bottom is appearing distorted due to the presence of the gray border at t ...

Delete chosen border from photo in html

I have a logo carousel on my website and when I click on one of the logos, a black outline appears indicating that it is selected. I've tried using img::selection { background: transparent; } but it didn't work as expected. I want to get rid of ...