bootstrap.native: How to Use Toast Component
In my previous post, I covered how to use bootstrap.native so you can drop the jQuery dependency right now. In this post, I'm gonna share how to use Toast component with bootstrap.native.
Toast UI

This popular UI component was added in Bootstrap 4.2. So first make sure you upgrade to 4.2+ to get the CSS.
I'm using bootstrap
gem in my Rails app. Update the version and run bundle
to install.
Then import the component's css.
Add "toast" to bootstrap.native loader:
That's all the setup.
How to use
A slim-down version of the markup from the official doc:
Initialize it from JavaScript like this:
That should display the toast and it'll disappear in a few seconds.
Breakdown
As the official doc says, "Toasts are opt-in for performance reasons, so you must initialize them yourself."
To do so in bootstrap.native, we first get the element by querying [data-dismiss=toast]
.
Then, we access the instance with toast["Toast"]
which can perform all the methods such as .show()
, .hide()
, and .dispose()
.
That is the syntax of accessing the component instance in bootstrap.native - element[string name of the component]
. It's much easier to take a look at the implementation of Toast and see how it stores the instance.
Integrate with Rails Flash
ActionDispatch Flash is a common way of setting notices or alerts after certain actions in the controller.
So far I've been using Bootstrap Alerts component to display the flash message. This time, I want to migrate it to the Toast component.
First, in a partial erb, we filter flash
enumerable and find :alert
or :notice
type of messages.Then we can use the type as part of the css to style them differently. We can also specify data-delay="3000"
so the Toast message automatically disappears in 3 seconds.
Go back to our JavaScript and add a presence check. There is only one Toast message at a screen for now.
Finally, render the partial in the main layout file.
I'll leave the css up to you .
That's it. Now you can use Flash alert and message just like before and they'll be displayed in the Toast component transparently.
Hope you find it useful. Thanks for reading.
Clap to support the author, help others find it, and make your opinion count.