Reputation: 365
For example I've this CSS code to handle a simple animation:
And my React component to render a simple list and change the list with Random values:
class App extends React.Component {
constructor() {
super();
this.state = {
items: ["Alex", "David", "John"]
};
}
change() {
this.setState({
items: [Math.random(), Math.random(), Math.random()]
});
}
render() {
return (
<div>
{this.state.items.map((item, index) => (
<p className="flasher" key={index}>
{item}
</p>
))}
<button onClick={this.change.bind(this)}>Change</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("react"));
@keyframes flasher {
from {
background: red;
}
to {
background: green;
}
}
.flasher {
display: block;
animation: flasher 0.5s;
background: red;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react" />
After clicking on Change button I've one Render into browser console but CSS animation not works in this case ... and only I've that CSS animation for first time render.
So, How can I apply CSS animation to every changes?
Apparently this code only changes innerText
and not re-render the element to apply that CSS effect. You know, I need this flasher effect for a socket service. that socket returns changes and I want to apply flasher for creating a simple attention for user.
Thanks
Upvotes: 4
Views: 5113
Reputation: 8213
If you want to reset components and animation. One of the trick you can use to make React to remount it. The easiest way to to remount is to change the key of a component after each button click.
For example instead this:
<p className="flasher" key={index}>
use the item as key:
<p className="flasher" key={item}>
It will do the trick. https://codesandbox.io/s/hopeful-hertz-rpqv2
Upvotes: 4