thomasbrus

thomasbrus

Building a dynamic select component (in Phoenix LiveView?)

Hi all,

I’m curious how you would go about the following. I have integrated a React component (Select | Mantine) to select players for a fantasy league team.

This works well but the issue is that each select contains about 600 players and these selects are rendered 11 times on the page.

And since the options are calculated server side and passed to the DOM via data attribute this creates a huge payload and slows down the browser when loading the page.

I tried to turn the React select into a remote select where it fetches the options from the backend but it got really bug, I don’t think this specific 3rd party component is suitable for that use case.

I’m curious if anyone has implemented something similar and what the approach was. Basically I have two options in mind for now:

You’d think that in 2022 it is not so difficult to build a select such as this one but no :smile:

Most Liked

derek-zhou

derek-zhou

You don’t need React for this. Just build the datalist server side, with the few letters typed by the user as the search criteria to filter down the list to a manageable size. This is one of the cases where Liveview’s live form validation really shines.

thomasbrus

thomasbrus

One alternative to using dynamic selects is allowing user to select players from bigger list is -
popup with input search panel with table below and allowing users to search and select from there.

Yes that is indeed an option. Although you would somehow need to connect the selected item in the modal back to the form / hidden input.

By the way, I just came across this post which is a bit more what I’m looking for:

My concern though is that there are certain frontend behaviours (such as clicking outside the dropdown to close it) that are not included in this blog post.

And I am not convinced the server should be contacted for such behaviour :thinking:

thomasbrus

thomasbrus

^ I just realized you can solve this client-side via phx-click-away and LiveView.JS :slight_smile:

Last Post!

thomasbrus

thomasbrus

I ended up solving it via an async react-select, the react component from Mantine that I was using before just didn’t work well with async data. So that removes the issue of having to load the payload in the DOM initially.

But yes initially it would add the entire payload to every select.

Here is the react-select implementation that I ended up using in case anyone is interested:

<.remote_select form={f} field={:player1_id} url={player_options_url(@conn)} options={Map.fetch!(@player_options, :player1)} placeholder={select_player_placeholder()} />
... etc ...
  def remote_select(assigns) do
    ~H"""
    <.form_field {form_field_assigns(assigns)} ><.remote_select_tag {remote_select_assigns(assigns)} /></.form_field>
    """
  end

  def remote_select_tag(assigns) do
    assigns =
      assigns
      |> assign(:error, error?(assigns.form, assigns.field))

    ~H"""
    <.react controller="remote-select" props={extra_attributes(assigns)}>
      <%= Phoenix.HTML.Form.hidden_input(@form, @field, data: [remote_select_target: "input"]) %>
      <div data-remote-select-target="component"></div>
    </.react>
    """
  end

react/1 is a simple functional component that adds a div with display: contents, adds a Stimulus data-controller attribute and serializes props (converting underscore to camelcase, and so on.)

The remote-select Stimulus controller:

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    static values = { props: Object };
    static targets = ['input', 'component'];

    connect() {
      ReactDOM.render(
        <RemoteSelect {...this.propsValue} defaultValue={this.defaultValue} onChange={this.handleChange} />,
        this.componentTarget
      );
    }

    disconnect() {
      ReactDOM.unmountComponentAtNode(this.componentTarget);
    }

    handleChange = (option) => {
      // prettier-ignore
      this.inputTarget.value = option === null ? '' : [].concat(option).map(o => o.value).join(',');
    };

    get defaultValue() {
      return this.propsValue.options.find((option) => option.value == this.inputTarget.value);
    }
  };

Notice how it concatenates values via ‘,’ in a single hidden input (in case multiple options are selected).

And finally the react component:

import React from 'react';
import AsyncSelect from 'react-select/async';
import { withTheme, withDefaults } from './react_select';

function RemoteSelect({ url, options, ...restProps }) {
  const loadOptions = (query) => {
    const remoteUrl = new URL(url);
    remoteUrl.searchParams.set('query', query);
    return fetch(remoteUrl.toString()).then((response) => response.json());
  };

  return (
    <AsyncSelect
      {...restProps}
      defaultOptions={options}
      noOptionsMessage={({ inputValue }) => (inputValue ? `Geen resultaten voor "${inputValue}"` : 'Type om te zoeken')}
      loadOptions={loadOptions}
    />
  );
}

export default withTheme(withDefaults(RemoteSelect));

Not much special going on here either except that it uses the url property to perform the async request :slight_smile:

Where Next?

Popular in Questions Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42716 114
New

We're in Beta

About us Mission Statement