Initiate CSS animation upon modification of component properties

I am looking for a way to create a fade in/out effect on a component whenever its prop changes. Unlike basic examples that toggle styles based on boolean conditions, I want the element's visibility state to be updated directly through prop changes.

For instance, in my code sandbox project, I have several buttons that, when clicked, will change the displayed text. I would like to implement a feature where this text fades in and out each time a user selects a different option.

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      current: "dog",
      isVisible: false
    };
  }

  componentDidMount() {
    this.setState({ isVisible: true });
  }

  handleOnClick = option => {
    this.setState({ current: option });
  };

  // used solely for testing CSS transition
  forceToggleState = () => {
    this.setState(prevState => ({ isVisible: !prevState.isVisible }));
  };

  render() {
    const options = ["dog", "cat", "rabbit"];
    return (
      <div>
        {options.map((option, index) => (
          <button onClick={() => this.handleOnClick(option)} key={index}>
            {option}
          </button>
        ))}
        <div style={this.state.isVisible ? styles.toggleIn : styles.toggleOut}>
          {this.state.current}
        </div>
        <button onClick={this.forceToggleState}>toggle me</button>
      </div>
    );
  }
}

const styles = {
  toggleIn: {
    opacity: 1,
    transition: "all 0.5s ease",
    border: "1px solid red"
  },
  toggleOut: {
    opacity: 0,
    transition: "all 0.5s ease-in"
  }
};

Visit the CodeSandbox link for the live example.

Answer №1

Solution: https://codesandbox.io/s/react-tutorial-abc123

I made some adjustments to your sandbox in order to achieve the expected outcome.

  1. Relocate the options array into the state section
  2. Send this.state.current as a prop to an Option component
  3. Develop a toggleOut animation using @keyframes to generate the intended visual effect
  4. Assign the key prop to this.props.current within the Option component to ensure the DOM element refreshes every time this.props.current changes. This will allow our animation to trigger with each alteration in this.props.current.

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

Ways to detect when the window printing process has been completed

Within my application, I attempted to generate a voucher page for the user using the following code: var htm ="<div>Voucher Details</div>"; $('#divprint').html(htm); window.setTimeout('window.print()',2000); The &apo ...

I created an image that can be clicked on, but unfortunately it only functions properly on the

I am currently working on creating an image that can be clicked to cycle through different images all within the same frame. While I have managed to get it to work, I am facing a limitation where it only responds to one click. count = 1; function myF ...

What is the best way to input information into an object?

I am having an issue where I am trying to add data into an object, but I keep getting the error "push is not a function". Here is the object in question: var item = { "_id": { "$oid": "asdf976" }, "Categories": [{ "mainmodels": [{ "su ...

AngularJS is throwing a $injector:modulerr error and I've exhausted all possible solutions

I recently started learning Angular and I've been following the tutorial on the official AngularJS website. Here's what I've tried so far: Installed angular-route and included the script below angular.min.js Utilized ngRoute in my mod ...

What's the best way to utilize multiple environment files in a Next.js application?

To dynamically change the base URL of an external backend API based on the environment, you can set different URLs for different environments. For example, .env.local=local.com, .env.staging=staging.com, .env.production=production.com To achieve this, you ...

Does shouldComponentUpdate returning `true` have the same effect as not having shouldComponentUpdate at all?

Within my React Native component, I have included a blank shouldComponentUpdate shouldComponentUpdate(nextProps, nextState) { } I am aware, from reading this answer, that an empty shouldComponentUpdate function helps in eliminating unnecessary re ...

Strange spacing issues with inline-block elements and struggling to vertically center content within them

I feel like I'm losing my mind trying to figure this out... any help would be greatly appreciated. There are three divs on the page that need to sit on a single line. They must be square with rounded corners, so setting width and height is necessary ...

Using Jquery slideToggle is creating additional spacing between inline-block divs

I am struggling with displaying a list of cities in an inline format. <div class="accordion-container"> <a href="#" class="accordion-toggle">London</a> <div class="accordion-content"> <p>Inform ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

Is it necessary to mark all checkboxes in the initial column of the gridview?

I have encountered an issue with my code that checks all checkboxes in the first column of a gridview. It seems to work only for Internet Explorer versions 5.0 to 8.0, but gives a Javascript error when running on IE 9 and above stating "Function Expected ...

Show information upon opening

I am currently working on a project that involves 4 different divs, and I need the content of each div to be displayed based on dropdown selection. I found a code snippet that was close to what I needed, but after trying to adjust it, I haven't been a ...

Opacity filter malfunctioning

It seems that the filter: opacity property is not functioning as expected in IE8. Despite having used it successfully before, I am currently facing issues with its implementation. Strangely enough, Firebug does not display the filter rule at all; only norm ...

Efficiently refine your search using the combination of checkboxes and dropdown menus simultaneously

I am currently in the process of creating a highly sortable and filterable image gallery that utilizes numerous tags. The inspiration for this project stems from a similar question on Stack Overflow regarding dropdown menus and checkboxes. You can view the ...

Creating a JSON structure using an array in Typescript

Here is an example of my array structure: [ { "detail": "item1", "status": "active", "data": "item1_data" }, { "detail": "item2", "status": ...

Error: You're trying to access the property 'hasOwnProperty' of an undefined variable in react-dom.production.min.js at line 760

Encountering an error while attempting to open my build project Interestingly, the project functions perfectly in development mode. Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined at Object.<anonymous> (react-do ...

What is the correct way to modify object properties within a Mongo Schema?

My MongoDB model structure is as follows:- var mongoose = require("mongoose"); const postModel = new mongoose.Schema({ postId: { type: String, unique: true, required: true }, authorId: { //other fields ...

Unlocking Discord Account Information through OAuth2

Currently, I am in the process of developing a moderation bot for Discord. I am working on implementing a paid plan and as part of that, I require users to log in with their Discord account using OAuth2. This allows me to retrieve user data and identify wh ...

Struggling to find the right match, Mongoose updates conditions with incorrect

Data Model const SurveySchema = new Schema({ title: { type: String, trim: true, required: true }, questions: [ { text: { type: String, trim: true, required: true }, answers: { type: Number, default: 0, min: 0 }, } ], date: { ty ...

Dynamically setting CSS values with jQuery to center an image within a div

I'm trying to center an image in a div according to the width of the image after I scale it to have a height of 250px. For example, if I had an image with dimensions 625x450 and, in my CSS file, set the height of the image to be 250px, then the width ...

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...