Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple css animation not working on dynamic reactjs element

Check the snippet at codepen http://codepen.io/anon/pen/EZJjNO Click on Add button, it will add another item but its appearing immediately without any fade effect.

JS:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.addItem = this.addItem.bind(this);

    this.state = {
      items: [1,2,3]
    }
  }

  addItem() {
    var items = this.state.items;
    items.push(4);
    this.setState({
      items: items
    })
  }
  render() {
    return (
      <div className="App">
        {
          this.state.items.map(function(i) {
            return <div className="item fade">Testing</div>
          })
        }
        <button onClick={this.addItem}>Add</button>
      </div>
    );
  }
}

React.render(<App />, document.body);

CSS:

.App {
  background-color: rgba(0,0,0, 0.5);
  text-align: center;
  height: 100vh;
}
div.item {
  border: 1px solid #ccc;
  padding: 10px;
  background: #123456;
  color: #fff;
  opacity: 0;
  transition: all 0.4s ease-out;
}
.fade {
  opacity: 1 !important;
}
like image 728
coure2011 Avatar asked Apr 09 '26 22:04

coure2011


1 Answers

Since the fade class is added by default, you don't get the transition effect. If you open your browser's developer tools and remove the class, you'll see it fade away nicely.

There's a few ways to get what you want, but I'd just use a keyframe CSS animation like so:

.fade {
  animation: 0.4s ease-out fadeIn 1;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    visibility: hidden;
  }
  100% {
    opacity: 1;
    visibility: visible;
  }
}

Here's a fork of your code pen showing how it works :)

like image 197
Kris Selbekk Avatar answered Apr 12 '26 12:04

Kris Selbekk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!