A
A
aliekoff2021-12-29 13:19:23
JavaScript
aliekoff, 2021-12-29 13:19:23

How to show notification in React for 3 seconds and hide?

The usual question is, I do a program like tinder and when you put a like, you just need to show a notification or animation for a few seconds that the like has been made. How can this be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shsv382, 2021-12-29
@aliekoff

to trigger a notification, you add a checkbox in the state of the type in the parent component:

this.state = {
    isAlertVisible: false
}
// ...
<Alert isVisible={this.state.isAlertVisible} />

Accordingly, on some event you make this flag true. Alternatively, you can write setTimeout in the same handler, which will change it back to false
handleClick = event => {
    // ...
    this.setState({isAlertVisible: true}, () => {
        setTimeout(
            () => {this.setState({isAlertVisible: false})}, 
            3000
        )
    })
}

Do not forget that setState is an asynchronous function, so I put the timer in a callback

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question