Create globally reusable live components using tailwindcss for phoenix web app
- User
Create globally reusable live components using tailwindcss for phoenix web app
- Assistant
Create globally reusable live components using tailwindcss for phoenix web app
Creating globally reusable Live Components in a Phoenix web application using Tailwind CSS involves several steps:
Below is a step-by-step guide to help you through the process.
Before creating components, ensure that Tailwind CSS is properly set up in your Phoenix application.
Navigate to your project's assets directory:
cd assets
Install Tailwind CSS via npm:
npm install tailwindcss postcss autoprefixer --save-dev
Generate the Tailwind configuration file:
npx tailwindcss init
This creates a tailwind.config.js file in your assets directory.
Edit the tailwind.config.js to specify the paths to all of your template files:
module.exports = {
content: [
'../lib/**/*.{ex,heex,eex,leex}', // Adjust the path based on your project structure
'./js/**/*.js',
],
theme: {
extend: {},
},
plugins: [],
}
Create a css/app.css file if it doesn't exist, and include the Tailwind directives:
@tailwind base;
@tailwind components;
@tailwind utilities;
brunch-config.js or webpack.config.jsIf you're using Webpack (Phoenix 1.6+ uses esbuild by default), you might need to update the configuration to process Tailwind's directives. Since Phoenix 1.6+, the default asset bundler is esbuild.
For Phoenix with esbuild, install esbuild plugins:
npm install esbuild esbuild-style-plugin --save-dev
Update your config/config.exs to instruct esbuild to process CSS:
# config/config.exs
config :esbuild,
version: "0.14.0",
default: [
args: [
"js/app.js",
"--bundle",
"--loader:.png=file",
"--loader:.jpg=file",
"--css",
"--outdir=../priv/static/assets"
],
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
Ensure your watchers in config/dev.exs are monitoring the assets:
watchers: [
npm: [
"run",
"watch",
cd: Path.expand("../assets", __DIR__)
]
]
Phoenix LiveView provides function components and stateful LiveComponents for building reusable UI components.
Function components are stateless and suitable for simple reusable UI parts.
# lib/my_app_web/components/hero_component.ex
defmodule MyAppWeb.HeroComponent do
use Phoenix.Component
def hero(assigns) do
~H"""
<section class="bg-gray-100 py-8">
<div class="container mx-auto px-6">
<h1 class="text-3xl font-bold mb-2"><%= @title %></h1>
<p class="text-gray-700"><%= @subtitle %></p>
</div>
</section>
"""
end
end
For components that require state or event handling, use LiveComponent.
# lib/my_app_web/live/components/modal_component.ex
defmodule MyAppWeb.ModalComponent do
use Phoenix.LiveComponent
def render(assigns) do
~H"""
<div id="modal" class="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-75">
<div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-lg sm:w-full">
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<%= render_slot(@inner_block) %>
</div>
<div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button phx-click="close" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
Close
</button>
</div>
</div>
</div>
"""
end
def handle_event("close", _params, socket) do
send(self(), :close_modal)
{:noreply, socket}
end
end
With Tailwind CSS set up, you can use its utility classes directly in your component templates.
For example, in the HeroComponent:
<section class="bg-gray-100 py-8">
<div class="container mx-auto px-6">
<h1 class="text-3xl font-bold mb-2"><%= @title %></h1>
<p class="text-gray-700"><%= @subtitle %></p>
</div>
</section>
Tailwind's classes like bg-gray-100, text-3xl, font-bold, etc., style your components without writing custom CSS.
To make your components globally reusable:
Place Components in a Centralized Directory: Store all your components in a dedicated directory like lib/my_app_web/components/ or lib/my_app_web/live/components/.
Alias Components in my_app_web.ex: Update your MyAppWeb module to automatically import or alias your components.
# lib/my_app_web.ex
defmodule MyAppWeb do
# ...
defp view_helpers do
quote do
# Import LiveView helpers
import Phoenix.LiveView.Helpers
# Import your components
alias MyAppWeb.{HeroComponent, ModalComponent}
# If you have many components, you can import all modules from components directory
import MyAppWeb.Components
end
end
end
In a .heex template:
<.hero title="Welcome to MyApp" subtitle="Building awesome apps with Phoenix and LiveView" />
In your LiveView module:
defmodule MyAppWeb.PageLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
{:ok, assign(socket, show_modal: false)}
end
def handle_event("open_modal", _params, socket) do
{:noreply, assign(socket, show_modal: true)}
end
def handle_info(:close_modal, socket) do
{:noreply, assign(socket, show_modal: false)}
end
end
In the template:
<%= if @show_modal do %>
<.live_component module={MyAppWeb.ModalComponent} id="modal">
<:inner_block>
<h2 class="text-xl font-bold">Modal Title</h2>
<p>Modal content goes here.</p>
</:inner_block>
</.live_component>
<% end %>
<button phx-click="open_modal" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded">Open Modal</button>
Slot Attributes: Use slots in components to allow flexible content insertion.
Component Configuration: Pass parameters to components via assigns to make them configurable.
Testing Components: Write tests for your components to ensure they behave as expected when used globally.
Documentation: Document your components for easier reuse by you or team members.
By following these steps, you can create a library of globally reusable Live Components styled with Tailwind CSS that you can use throughout your Phoenix application, enhancing consistency and productivity in your development workflow.
Not yet included in a published release.