I'm learning react. In the below Alert component I'm updating a simple alert message and setting the opacity to 1 and then fading it out with a CSS transition. This is in a simple to do app to get ramped up on react.
The issue I'm having is when I update the alert text this.props.message
the previous message text shows for a fraction of a second after opacity is set to 1, before the new message replaces it. It is very quick but it seems like there is a race condition as the DOM or React renders the text change slower than the style change. Let me know if there is a way I can omit the hiccup and set opacity after the text message has changed. Thanks.
var TodoApp = React.createClass({
getInitialState: function() {
return {
items: [],
alert: { message: '', success: null }
};
}
genericMethod: function() {
...
this.setState({ alert: { message: message, success: true } });
...
},
...
render: function() {
return (
<div>
<Alert message={this.state.alert.message} success={this.state.alert.success} />
<ItemInput onItemSubmit={this.addItem} />
<ItemList items={this.state.items} deleteItem={this.deleteItem} toggleComplete={this.toggleComplete} />
</div>
);
}
});
...
var Alert = React.createClass({
delayTime: 1000,
getInitialState: function() {
return {
visible: false
};
},
componentWillReceiveProps: function() {
this.setState({ visible: true }, function() {
this.setTimer();
});
},
setTimer: function() {
setTimeout(function(argument) {
this.setState({ visible: false });
}.bind(this), this.delayTime);
},
render: function() {
var style = {
opacity: (this.state.visible ? 1 : 0),
transition: 'opacity '+(this.state.visible ? 0 : this.delayTime)+'ms'
};
var alertClass = 'alert'+(this.props.success ? ' success' : ' error');
return (
<div className={alertClass} style={style}>
{this.props.message}
</div>
);
}
});