Easiest Way To Add Toaster inside Phoenix/Elixir App
So I’ve been finding the easiest way to integrate toaster in my phoenix app, and now I think I found one.
Prerequisite:
- React JS inside your phoenix/elixir app: react_phoenix
- A toaster you want to integrate: Cogo Toast — my toaster
Once you’re done setting up react-phoenix, we can now create JS and render it to our Html pages. But let us first set up our toaster.
On your Controller Method make sure to add a put_flash
in your conn pipeline
conn
|> put_flash(:success, "Successfully shortened links") <- or :error
Now create a toast.html.eex
and paste this code, in my case I created it inside /template/shared/
.
<%= unless is_nil(get_flash(@conn, :error)) do %>
<%= ReactPhoenix.ClientSide.react_component("Components.Toast", %{message: get_flash(@conn, :error), flash_type: "error"}) %>
<% end %>
<%= unless is_nil(get_flash(@conn, :success)) do %>
<%= ReactPhoenix.ClientSide.react_component("Components.Toast", %{message: get_flash(@conn, :success), flash_type: "success"}) %>
<% end %>
We’re only doing success and error toast for now. ReactPhoenix.ClientSide.react_component
is how you render a react js file in Html pages, you can also pass props inside like message and flash_type
, that we’ll make use of later on in our react component.
Next, render toast.html.eex
inside the main layout /layout/app.html.eex
<%= render YourWeb.SharedView, "toast.html", conn: @conn %> <-- Paste this anywhere inside app.html
Now let's create the Toast
Component in React
inside /assets/js/
create a file toast.js
then paste this code:
import React, { Component } from 'react'
import cogoToast from 'cogo-toast'export default class Toast extends Component{componentDidMount(){
const { message, flash_type } = this.props
this.returnFlash(message, flash_type)
}returnFlash(message, type) {
let options = {
hideAfter: 5,
position: 'top-right'
}switch (type) {
case "success":
return cogoToast.success(message, options)
case "info":
return cogoToast.info(message, options)
case "warn":
return cogoToast.warn(message, options)
case "error":
return cogoToast.error(message, options)
default:
return cogoToast.loading(message, options)
}
}render() {
return null
}
}
In this code, I’ve created a returnFlash()
function with message and type parameters that I got from this.props
(from toast.html
earlier)
And Finally, make sure to import toast.js
and render it as window component inside the main app.js
import Toast from './toast'window.Components = {
Toast
}
And that's about it. Run your app and you should see the toaster.
If you find this helpful, I’d appreciate a coffee 😊