reactstrap alert automatic hidden

Viewed 16158

I am new in React and I use Alert - Dismissing from Reactstrap , I need the alert to automatically disappear after 2s. I tried to find some function that could be done, but unfortunately I did not. Thank you for help

3 Answers

Please have a look at this code, hiding alert after a specific time

when you want to show the alert on some action, you can enable a state associated with that alert and disable it when you want to hide it.

I had a similar problem. My purpose was to show an Alert message after a Modal closed. I am using react-bootstrap for Modal and Alert component with useState and use Effects hooks.

const [visibleAlert, setVisibleAlert] = useState(false); --> init state

const handleVisible = () => { ---> Last State for Alert
    setAlertVisible(true)
    setTimeout(() => { ---> 2 seconds later which is closing
        setAlertVisible(false)
    }, 2000);
} 

useEffect(() => {

    handleClose();  ----> This is for Modal
    return () => {
    handleVisible();  ---> This is for Alert message
};

And this is my Alert component.

<Alert show={visibleAlert} variant="success"} dismissible>
    Employee List Updated Successfully.
</Alert>

Alerts are something I like to play with: here is a full dynamic example where I set 1 alert and control it based on my requirements.

1st we need to set the alert. If you are using reactstrap use capital A for alerts

<Alert color={this.state.alertColor} isOpen={this.state.Alertvisible} toggle={(e) => this.setState({Alertvisible: false})}> {this.state.message} </Alert>

as you can see I can dynamically control the color, the visibility and the content of the alert without having to set multiple alerts.

here is the part where I control the alert

this.setState({
            
Alertvisible: true, 
alertColor: 'success', 
message: 'Alerts are awesome!'}, 

()=> {window.setTimeout(()=>{this.setState({Alertvisible:false})},8000)
});

So let me explain what is going on here! with alertvisible: true we show the alert, with alertcolor: we set the color according to the reactstrap or bootstrap message: here we put the content of what we want to display

at the end you notice the window.setTimeout(()=> this is set to timeout in 8000 (8 seconds)

don't forget to add your states in the constructor.

I hope this helps :D

Related