We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Auto-disappearing flash messages in Phoenix LiveView
almirsarajcic
Use this LiveView hook to make flash messages automatically disappear after 5 seconds in your Phoenix app.
Create the JavaScript hook file:
// assets/js/hooks/flash_auto_disappear.js
export default {
mounted() {
setTimeout(() => {
this.el.click()
}, 5000)
}
}
Import and register the hook in your app.js
:
// assets/js/app.js
import FlashAutoDisappear from "./hooks/flash_auto_disappear"
let Hooks = {
FlashAutoDisappear: FlashAutoDisappear
}
let liveSocket = new LiveSocket("/live", Socket, {
hooks: Hooks,
params: {_csrf_token: csrfToken}
})
Add the hook to your existing flash component:
# lib/my_app_web/components/core_components.ex
~H"""
<div
phx-hook="FlashAutoDisappear"
# ... other attributes
>
# ... content
</div>
"""
The messages fade out smoothly and are properly cleared from the LiveView flash state, providing a polished user experience.
Notice we used this.el.click()
inside the hook to reuse the component’s phx-click
handler. That way, we avoided code duplication.
Copy link
copied to clipboard