...

/

How to Build The Demographic Form

How to Build The Demographic Form

Let's learn how to render and implement a component in a stateless LiveView.

The first part of the survey is the demographic section, and we’ll wrap up that section in a component. First, we’ll review how to implement and render a stateless component. We’ll build a stateless component and render it within the SurveyLive LiveView. Then, we’ll dive into the component’s lifecycle. We’ll set the necessary component state and use it to render the form for creating a demographic.

Let’s do a quick refresher. Remember, we’ll render a component with live_component/3 with a socket, the component module, and some assigns. A component is stateless if it doesn’t have an :id key in assigns. That means the component can be pretty simple, often with nothing more than a update/2 function and a template or a render.

Calling a stateless component in a LiveView

Let’s start by calling a stateless component in our SurveyLive template. To do so, we open up the pento/lib/pento_web/live/survey_live.html.leex, and add this:

Press + to interact
<section class="row">
<%= live_component @socket, PentoWeb.DemographicLive.FormComponent, content: "Hello to the Demographic Form Component" %>
</section>

This won’t work because we haven’t built the DemographicLive.FormComponent yet. Still, we know where to put the new code. We’re starting dead simple, with a stateless component. We can tweak it to do what we want as we go.

Our next step is to define the DemographicLive.FormComponent in pento/lib/pento_web/live/demographic_live/form_component.ex, like this:

Press + to interact
defmodule PentoWeb.DemographicLive.FormComponent do
use PentoWeb, :live_component
end

Now add a corresponding template, in pento/lib/pento_web/live/demographic_live/form_comp ...