Issue with implementing slide animations in Reactjs when target dimensions are not predetermined

Im implementing animations in my react app to enhance the user experience. I am trying to achieve a slide-in effect for a div to appear and a slide-out effect for it to disappear.

My current tech stack includes bootstrap 5.1.0 and react-bootstrap 1.6.1.

One solution I have come up with is wrapping the content within a div and toggling its maxHeight property between window.innerHeight and 0 as needed. Additionally, I applied a custom CSS class:

.transition-height{
    transition: max-height 0.5s ease-in-out;
}

The issue I am facing is that when I close the div, there is a delay due to the animation starting from a high value of maxHeight. Since the height target is dynamic based on the content length, I used window.innerHeight.

You can view the code behavior on codesandbox.

Any suggestions on how to resolve this issue?

Answer №1

If you're facing a situation where you just need to determine the height of the div using useRef, and then set the current height when show = true. Check out this codesandbox example.

AppearDiv

const AppearDiv = (props) => {
  let { show = false, className = "", style = {} } = props;
  const ref = useRef(null);
  const getPaperBoxHeight = ref.current?.scrollHeight || 0;

  const filteredProps = Object.entries(props)
    .filter(([k, _]) => !["className", "show", "style"].includes(k))
    .reduce((p, [k, v]) => ({ ...p, [k]: v }), {});

  style = show ? { height: getPaperBoxHeight } : { height: 0 };
  return (
    <div
      ref={ref}
      className={
        "overflow-hidden transition-height" + (className && ` ${className}`)
      }
      style={style}
      {...filteredProps}
    />
  );
};

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

What is the method for increasing the left margin of the back button on the default header in React Native?

My attempt to increase the space on the back button from the left side of the header in my React Native code has been unsuccessful. headerStyle: { paddingLeft: 60 } https://i.stack.imgur.com/0RFb0.png I also experimented with adding margin ...

Having trouble containerizing a Vite React-Typescript project with Docker

I'm currently in the process of dockerizing a Vite React-Typescript boilerplate setup, but I'm encountering difficulties connecting to the container. Here's how I installed the vite-react-typescript boilerplate: npm init vite@latest vite-d ...

Using the spread operator to include a new key within a looping structure

In my current state, I have a list of questions structured like this: this.state = { questionListData: [ { id: 1, question: "Who was the first man to step on Moon?", options: [ { opt: "Abdul Kalam" }, ...

Utilize CSS to ensure that the hover effect of the main navigation remains active even when the mouse hovers over the sub-menu

Is there a way to make the hover state in navigation items persist when the mouse hovers over a sub-menu? Currently, when hovering over a top-level nav item, the link color changes to white and background turns black, but this reverts back once the mouse m ...

What is the best way to perfectly center a div both vertically and horizontally?

Despite being new to CSS, I've experimented with various approaches but am struggling to center my div vertically. Parent : #ModalScroll{ position:absolute; top:0; left:0; z-index:1001; height:1px; width:1px; overflow:hi ...

Utilize TypeScript function types in React for enhanced functionality

I have made the decision to refactor a project that was originally created with vanilla JavaScript and now I want to transition it to TypeScript. One issue I am facing is how to pass a function as a type on an interface. Although I referred to the TypeScr ...

I am experiencing an issue where the table-striped class is not applying alternate colors to the

I wanted to add alternating colors to my table, but unfortunately all rows turned grey once I applied the table-striped class. I even attempted to load both the v3 and v4 bootstrap CSS files, but the issue persisted. HTML <table id="maxDivers ...

I am integrating Material-UI's flat pagination feature into my React project

Looking for advice on implementing pagination logic in my application. I am fetching a list of jobs from the freelancer api and using https://www.npmjs.com/package/material-ui-flat-pagination to handle pagination. The page numbers are displaying correctly ...

Sort the DOM elements in jQuery based on their CSS color property

Displayed on the page below is a list of usernames in a random order. I'm looking to sort them using jQuery in the following sequence: red blue green purple black This is my current progress: <script type="text/javascript"> $(function() { ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...

Sticky Position Not Functioning Properly in Flexbox Layout

I've attempted to use align-self: flex-start, but it had no effect. The main flex container is on the right side of my page (flex-direction: column) and I want one block of flex columns to stick once I scroll down to them. I enclosed a container aroun ...

useEffect is triggered despite there being no change in the state

const [urlList, setUrlList] = useState(0); const callDayList = () => { console.log(urlList); Axios.post('http://localhost:3001/api/get', { passNum: urlList, }); }; useEffect(callDayList, [urlList]); <td> <Link ...

Updating display following a Pop action using react-native-router-flux

I'm facing a major issue with my debut React Native application. I've dedicated several hours today to troubleshooting, but unfortunately, none of the solutions seem to work for me. The problem lies within two views: <Router> <Stac ...

Use JavaScript to load and set a background image for a div

When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that. $(window).load(function() { var randomImages = [&apo ...

Troubleshooting in Vercel: Unable to render PNG file in Next.js

While working on a project using Next.js and Sass, I encountered an issue when deploying it on Vercel. The PNG images did not render properly, whereas the SVG files displayed without any problems. Interestingly, the PNG images render fine in my localhost ...

The dynamic routing page does not load when the browser back button is used in Next.js

Currently, I am facing an interesting challenge in my Next.js project. The issue arises when I receive a new URL path from an external API and need to update this path in the browser without triggering a page reload. To achieve this, I am utilizing the Hi ...

After deploying on Google Cloud, the Google Places API is showing no results

I've created an app that utilizes the Google Places API for its functionality. The issue I'm facing is that the places load fine when testing the app locally, but once it's deployed on Google Cloud, the results don't show up. Even thoug ...

Is there a way to shift text upward while it is contained within a span element inside a list item?

In my code, I have the following setup: <li> <a class="dw"><span>Design Goals</span></a> </li> .dw { background-image: url(/Content/images/icons/fugue/document-globe.png); } However, when I check this in my browser ...

The slidedown feature is not functioning as initially planned

As a beginner in HTML, jQuery, and CSS, I am attempting to create a navigation bar that will trigger a jQuery slidedown effect when clicked. Unfortunately, my current code is not producing the desired outcome. Below is a snippet of what I have implemente ...

Using React to apply various filters to an array

Just getting started with react and working with an array of objects named arrayToFilter that I need to filter in multiple ways. Whenever a user changes the filter options, all filters should be applied to the array and the results should be stored in a fi ...