Struggling to implement a seamless scrolling effect using CSSTransition Group

In my quest to achieve a smooth vertical scroll effect for content appearing and disappearing from the DOM, I've turned to CSSTransitionGroup (or ReactTransitionGroup). While I'm familiar with CSS animations for such effects, I need to implement this in React when elements enter and leave the DOM. That's why I thought CSSTransitionGroup would be perfect.

Despite successfully animating properties like color and opacity, I'm facing difficulty in animating properties such as height or max-height to smoothly fade out content from top to bottom or vice versa. How can I animate this smooth scrolling effect for item entry and exit from the DOM?

Below is my current code using CSSTransitionGroup:

class App extends React.Component {
  state = {
    random: true
  };

  toggleItem = () => {
    this.setState({
      random: !this.state.random
    });
  };

  render() {
    console.log("random", this.state.random);
    return (
      <div>
        <button onClick={this.toggleItem}>toggle item</button>
        <br />
        <CSSTransition
          in={this.state.random}
          timeout={400}
          classNames="alert"
          unmountOnExit
          appear
          enter={false}
        >
          <div class="back">
            Hello adsffd asdfadfs asdfasd asdfasdf asdfasfa fdasfas asdfasdf
            afdsafas asdfasd asdfasdf asdfadsf asdfads asdfads asdfasdf
            asdfadsadsf world Hello adsffd asdfadfs asdfasd asdfasdf asdfasfa
            fdasfas asdfasdf afdsafas asdfasd asdfasdf asdfadsf asdfads asdfads
            asdfasdf asdfadsadsf world Hello adsffd asdfadfs asdfasd asdfasdf
            asdfasfa fdasfas asdfasdf afdsafas asdfasd asdfasdf asdfadsf asdfads
            asdfads asdfasdf asdfadsadsf world Hello adsffd asdfadfs asdfasd
            asdfasdf asdfasfa fdasfas asdfasdf afdsafas asdfasd asdfasdf
          </div>
        </CSSTransition>
      </div>
    );
  }
}
export default App;

Here's the current class for entry states:

.alert-enter {
  height: 0px;
  visibility: hidden;
  overflow: hidden;
}
.alert-enter-active {
  height: auto;
  overflow: auto;

  visibility: visible;
  transition: all 300ms;
}

Answer №1

To create a smooth transition effect for your text div, consider adding a white div as a wrapper and applying a transition to it.

class App extends Component {
state = {
    random: false
  };

  toggleItem = () => {
    this.setState({
      random: !this.state.random
    });
  };

  render() {
    return (
      <div>
        <button onClick={this.toggleItem}>toggle item</button>
        <br />
        <div className="back">
          Hello adsffd asdfadfs asdfasd asdfasdf asdfasfa fdasfas asdfasdf
          afdsafas asdfasd asdfasdf asdfadsf asdfads asdfads asdfasdf
          asdfadsadsf world Hello adsffd asdfadfs asdfasd asdfasdf asdfasfa
          fdasfas asdfasdf afdsafas asdfasd asdfasdf asdfadsf asdfads asdfads
          asdfasdf asdfadsadsf world Hello adsffd asdfadfs asdfasd asdfasdf
          asdfasfa fdasfas asdfasdf afdsafas asdfasd asdfasdf asdfadsf asdfads
          asdfads asdfasdf asdfadsadsf world Hello adsffd asdfadfs asdfasd
          asdfasdf asdfasfa fdasfas asdfasdf afdsafas asdfasd asdfasdf
          <CSSTransition
            in={this.state.random}
            timeout={1000}
            classNames="alert"
            unmountOnExit
          >
            <div className="white" />
          </CSSTransition>
        </div>
      </div>
    );
  }
}

style.css

.alert-enter {
  transform: translateY(400px);
}
.alert-enter-active {
  transform: translateY(0px);
  transition: all 1000ms;
}
.alert-exit {
  transform: translateY(0px);
}
.alert-exit-active {
  transform: translateY(800px);
  transition: all 3000ms;
}
.back {
  position: relative;
  overflow: hidden;
}
.white {
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: white;
  width: 100%;
}

You can view the implementation on CodeSandBox. Hopefully, this solution works for you!

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 remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...

If a single checkbox is selected within a group, then every other checkbox should be deactivated and deselected

Here is the code snippet provided: function listen(element, event, callback) { if (element.attachEvent) { element.attachEvent('on' + event, callback); } else { element.addEventListener(event, callback); } } var form = document.que ...

Retrieving a file URL from Sanity within a blocks array

I've been working on a website with Next JS and using Sanity as the CMS. While Sanity has schemas for images, I ran into an issue when trying to handle videos. The documentation recommends using GROQ queries to convert file URLs at the request level, ...

Exploring the features of useEffect and setState in hook functions

Exploring the idea of utilizing React to efficiently fetch data using useEffect correctly. Currently facing a situation where data fetching is occurring constantly instead of just once and updating only when there is an input for the date period (triggeri ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

Unable to select a checkbox in an ASP.NET Core MVC view

In the process of developing an ASP.NET Core 3.1 MVC application, I am faced with a task to implement a dynamic checkbox menu for selecting fruits and storing the choices in another data source. However, encountering an issue where I'm unable to sele ...

Error: An unexpected identifier was found within the public players code, causing a SyntaxError

As a newcomer to jasmine and test cases, I am endeavoring to create test cases for my JavaScript code in fiddle. However, I'm encountering an error: Uncaught SyntaxError: Unexpected identifier Could you guide me on how to rectify this issue? Below is ...

Opening new windows in Chrome after an AJAX request behaves like a pop-up

When a user clicks a button in my application, an ajax request is triggered. Following the success of this request, I generate a URL which I intend to open in a new tab. Unfortunately, when using Chrome and calling window.open within the success handler, t ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

Angular directive for concealing the 'ancestor' of an element

I have created a code snippet that effectively hides the 'grandparent' element of any '404' images on my webpage. Here is the code: function hideGrandparent(image){ image.parentNode.parentNode.style.display = 'none'; } < ...

What is the best way to retrieve a JSON object from within a nested JSON object within another parent object?

I am facing an issue with accessing a nested json object in JavaScript. The main json object contains another json object called "from", which in turn has a json object named value, and inside value is the address property that I need to access. Here' ...

Inserting images into an HTML table using JavaScript in real-time

I am attempting to dynamically add an image into a table, but I am encountering difficulties. Whenever I try to insert an image into a cell, I receive the following error message: Cannot access the inner content because it is not literal. if ...

Can you explain the process of utilizing Angular databinding to display nested information?

I'm facing a challenge with databinding when working with nested arrays in multiple timeslots and windows. Despite understanding the basics, I can't seem to make it work no matter how I try different approaches. It's really frustrating not k ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

The translation feature in React does not seem to be functioning properly with SASS

After trying various display settings like flex and block without success, I realized that the transform property was not working as expected. Despite centering elements successfully using other methods, the transform doesn't seem to have any effect o ...

Sending information from Ajax to PHP

Could anyone please explain the script provided above to me? I am attempting to pass the value of $user data so that I can utilize $_REQUEST['user'] within sort.php, but I am encountering difficulties. It seems to be passing in a long URL. $(fun ...

Eliminating redundant values from a JSON object that is nested within another

Currently, I am working on rendering a list of Labels from a local JSON file. However, I am facing the issue of duplicates and I want each label to appear only once. I attempted to use Array.filter() and other methods to achieve this line: "Categories": ob ...

Div containing a centered span with a background

<div> <span style= "background: red; text-align: center;"> There seems to be an issue here </span> </div> The text alignment is not functioning as expected. I need the text to be centered along with the background. https://jsfiddl ...

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

Error: Failed to parse the given color specification

My chrome extension is showing an error message: Unchecked runtime.lastError: The color specification could not be parsed. This error seems to be in the popup.html: 1 -> <! DOCTYPE html> line. Can anyone explain what this means and how to fix ...