Overview of the Phoenix and LiveView Collapse Component
The Collapse component provides a simple way to show and hide content with smooth animations. It's unstyled by default, allowing you to apply your own styling while providing the core collapsible functionality.
Note: The Collapse component is designed to be unstyled. You have complete control over the appearance of both the trigger and content elements. This makes it flexible for use in any design system while providing the core collapsible functionality.
Basic Usage
The simplest way to use the collapse component is with a trigger and content.
<!-- Basic collapse example --> <.collapse id="basic-collapse"> <:trigger> <button class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"> Toggle Content </button> </:trigger> <div class="p-4 bg-gray-100 mt-2 rounded"> This content will be hidden/shown when clicking the trigger button. </div> </.collapse>
Initially Open
You can set the collapse to be initially open by setting the
open
prop to true.
<!-- Initially open collapse --> <.collapse id="open-collapse" open={true}> <:trigger> <button class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"> Toggle (Initially Open) </button> </:trigger> <div class="p-4 bg-green-100 mt-2 rounded"> This content is initially visible when the page loads. </div> </.collapse>
Custom Animation Duration
Control the animation speed with the
duration
prop (in milliseconds).
<!-- Custom duration collapse --> <.collapse id="slow-collapse" duration={500}> <:trigger> <button class="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600"> Slow Animation (500ms) </button> </:trigger> <div class="p-4 bg-purple-100 mt-2 rounded"> This collapse animation takes 500ms instead of the default 200ms. </div> </.collapse>
Server Events
Enable server events to receive notifications when the collapse opens or closes.
Note:
If the
event_handler
is specified as a prop, the client will send data under that event name. Otherwise, data will automatically be sent to two events:
collapsible_close
and
collapsible_open
.
<!-- Server events collapse --> <.collapse id="server-collapse" server_events={true}> <:trigger> <button class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"> Server Events Enabled </button> </:trigger> <div class="p-4 bg-red-100 mt-2 rounded"> This collapse sends open/close events to the LiveView server. Check your browser's network tab to see the events. </div> </.collapse>