What is the best way to smoothly enlarge a div as new content is introduced?

Is there a way to smoothly expand a div when new content is added?

const [render, setRender] = useState(false)

    const showHide= () => {
        setRender(!render)
    }

  return (
    <div className="container">
      <h1>TEST CONTAINER</h1>
      {render && <Paragprah />}
      <button type="button" class="btn btn-primary" onClick={showHide}>Primary</button>
    </div>
  );
}

CSS

.container {
  margin-left: 30%;
  margin-top: 10%;
  width: 500px;
  height: auto;
  background-color: whitesmoke;
}

In the code above, a component is rendered when a button is clicked. However, when new content is added to the div, it expands instantly instead of smoothly. I need the expansion to be gradual. Click here to see an example video. A fixed height won't work for me as the content comes from an API and varies in length each time. Any suggestions on achieving a smooth transition while still accommodating dynamic content?

Answer №1

To achieve a seamless transition effect, consider utilizing the CSS property 'transition'.

transition: opacity 0.5s;

For additional guidance, check out this helpful resource.

Answer №2

Here is an updated version of the code that handles content with dynamic sizes. To track the size of the content being loaded, utilize the useRef hook to store this information in a variable and export it along with your component.

import { useRef, useEffect} from "react";

var ParagraphHeight;

function Paragraph() {
  const ref = useRef(null);

  useEffect(() => {
    // Store the height of the loaded content
    ParagraphHeight = ref.current.offsetHeight;
  }, []);

  return (
    <div ref={ref}>
      <p>Your content here for example...</p>
    </div>
  );
}

export { Paragraph, ParagraphHeight };

To implement this, import your Paragraph component and place it inside a .wrapper div with a default height of 0px (making the Paragraph hidden). Clicking on a button will then adjust the height of the wrapper to the ParagraphHeight value.

import { useState } from "react";
import { Paragraph, ParagraphHeight } from "./Paragraph.js";

export default function App() {
  const [isopned, setisopned] = useState(false);
  const [wrapperHeight, setWH] = useState(0);
  const showHide = () => {
    if (!isopned) setWH(ParagraphHeight);
    else setWH(0);
    setisopned(!isopned);
  };

  return (
    <div className="container">
      <h1>TEST CONTAINER</h1>
      <div className="wrapper" style={{ height: wrapperHeight }}>
        <Paragraph />
      </div>
      <button type="button" className="btn btn-primary" onClick={showHide}>
        Primary
      </button>
    </div>
  );
}

Ensure to update your CSS by adding overflow-y: hidden and a CSS transition to smoothly expand the wrapper div.

.container {
  margin-left: 30%;
  margin-top: 10%;
  width: 500px;
  background-color: whitesmoke;
}

.wrapper {
  display: grid; /*to prevent some problem caused by overflow hidden*/
  transition: height 1s linear;
  background-color: wheat;
  overflow-y: hidden;
}

Check out the live demo here

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 there a way to incorporate the load page plugin specifically for JavaScript while ensuring that my PHP code is still functional?

Is there a way to implement the loading page plugin "PACE" for PHP code execution instead of just JavaScript? I am more comfortable with PHP, CSS, and HTML, but not very experienced in JavaScript/AJAX. The PACE plugin is designed to show a progress bar fo ...

Are you making the most of data exchange between JavaScript and Node.js?

I've been doing some research but I haven't found the exact solution I'm looking for. Here's what I need: I want to generate data using client-side JavaScript, perform manipulations on it with server-side Node.js, and then send it back ...

How can I access the feed of a single user using the Facebook API

I have yet to experience working with Facebook APIs, but I am interested in developing a basic app that will display posts from a specific Facebook user. I would prefer not to enable login for multiple users, just keep it simple. My goal is to create an a ...

Creating lasting placeholder text with gaps between each word

Looking to create a unique text input with static content on the right and editable text on the left https://i.stack.imgur.com/K0YfM.png Any suggestions? ...

What is the optimal method for iterating through every element in a string array?

Within my code, I am dealing with an array named var mya = ["someval1", "someotherval1", "someval2", "someval3"];. The goal is to have a function that receives an object with a property set to one of these values. Instead of simply iterating over the arra ...

Create a filled Material UI icon symbol

For my React app utilizing the Material UI library, I have incorporated Icons as symbolic representations. By including the baseClassName: 'material-symbols-rounded' in all icons through the global theme.js file: MuiIcon: { defaultProps: { baseCl ...

Display a dropdown menu when hovering over with a delay

I recently created a basic navigation menu with dropdown functionality using CSS3 initially, but I decided to enhance it by incorporating jQuery to display the dropdown after a set timeframe. However, I am facing an issue where all dropdowns appear when ho ...

Harnessing the power of Bootstrap 4 with the magic of CSS transform

I'm trying to create a diamond shape with lines on the sides. It looks fine as a square, but when I use the transform: rotation(45deg); property, the lines end up crossing through the diamond instead of being beside it. Check out my code here ...

How do I use JQuery to target the preceding HTML element that shares the same class and type as the last element selected?

Consider the following code snippet: <div id="someId"> <select class="example"> <option value="1">some example</option> </select> <div class="example"></div> <select class="example"> <opti ...

How can I change the background color of a parent div when hovering over a child element using JavaScript

I am working on a task that involves three colored boxes within a div, each with a different color. The goal is to change the background-color of the parent div to match the color of the box being hovered over. CSS: .t1_colors { float: left; wid ...

Internet Explorer 11 is not interested in giving attention to a disabled element

I'm trying to limit text input to only one of two fields. My approach involves checking the value of a field when it loses focus, and then disabling the other field if the initial one is not empty. Below is an example: HTML: <div class="contain ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

Using JQuery to Evaluate HTML into an Element

When working with PHP pages, I often need to fetch data from another source and populate an input or textarea field. However, I encounter issues when dealing with HTML tags and apostrophes. In my experience, passing around HTML content using JavaScript ca ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

Utilizing X-editable and Parsley to trigger dual Ajax calls

Here is a snippet of code I am working with: $.fn.editable.defaults.mode = 'inline'; var editable = $('.x-editable').editable({ send: 'always', validate: function() { var form = editable.next().find('form ...

Performing bulk operations on multiple documents in MongoDB by specifying a custom identifier for updating or

Recently, I've been working with a mongo schema const taskSchema=new Schema({ userID:{type:ObjectId,required:true}, task: { type: String, required: true, trim: true, maxlength: 30, }, finalDate:{type:Date,required:true}, ...

Invalid controller function path specified in Laravel framework for AJAX request

I am struggling to find the correct ajax URL as the one I am currently using is not working. The console shows the following error message: GET XHR localhost:8000/Controller/getUnitSellingPrice [HTTP/1.0 404 Not Found 203ms] In the create.blade View: ...

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

Bootstrap 4: The mystery behind why the popover fails to appear inside a scrollable dropdown

Is there a way to replicate the behavior of Bootstrap 3 dropdowns with scrollbars on hover and popovers in Bootstrap 4? It seems that setting overflow:hidden; for scrolling functionality in dropdown menus also hides the popover. I have tried using containe ...