Reputation: 43
I'm trying to create a React component where I can call a function like showMessage(message, bgColor)
and an alert box will pop up that closes automatically after 5 seconds.
I've created many React components in my application but this one is causing me trouble because of having to call alert()
, it not always being present, and having a required timer functionality. I just can't think of a "React"ive way of designing the component.
Here is the current jQuery code that I'm using which works but I'm trying to get away from:
$("#alertBox").css('background-color', color);
$("#alertBox").html(message);
$("#alertBox").alert();
$("#alertBox").fadeIn(500, "linear").fadeOut(5000, "linear", function() {
$("#alertBox").alert('close');
});
The problem is React is fundamentally declarative and this code just seems so imperative. In certain event handlers in my codebase I want to be able to just call a function to momentarily display this alert box. If it wasn't for the call to the alert function and fading in/out it wouldn't be so bad (could just do conditional redner). This is the last place in my code I'm still using jQuery which I'm trying to completely neuter from my application.
I'd also rather not use react-bootstrap
and react-motion
because I just found out about them a couple days ago and this is the last React component I need for my application and rather not rewrite everything now to use those libraries.
Upvotes: 4
Views: 5553
Reputation: 4945
How about something like;
<showMessage message={message} bgcolor={bgcolor} hide={hideMessage}/>
then in showMessage render;
render() {
if (this.props.hide) return null;
if (this.state.timerDone) return null;
return (<div id="messageDive" style={whatever}></div>);
}
And you probably need something in componentReceivedProps to reset timerDone and set your timer. Then of course timerDone method to setState({timerDone: true}).
Upvotes: 2