themesberg / flowbite-svelte

Official Svelte components built for Flowbite and Tailwind CSS
https://flowbite-svelte.com
MIT License
2.22k stars 272 forks source link

Support actions on Input #1235

Open james-w opened 9 months ago

james-w commented 9 months ago

Summary

I'd like to be able to trigger focus changes to an input element. One way to do this is with a small action to call .focus() on the element, but arbitrary actions aren't exposed by the component.

Basic example

function focus(el) {
  el.focus();
}

<Input use:focus />

Motivation

When dynamically adding an input to the page I want to be able to focus it to allow the user to start typing.

autofocus is supported, but this doesn't always work depending on focus state of the page.

Alternatively, exposing a ref to the html element would allow the function to be called in a different way.

Thanks for your work on the library, it's been great to use so far!

hardyjosh commented 8 months ago

@james-w afaik you can't use the use directive with components, only HTML elements. So it would have to be something like

function focus(el) {
  el.focus();
}

<Input action={focus} />
TopherTimeMachine commented 6 months ago

@james-w afaik you can't use the use directive with components, only HTML elements. So it would have to be something like

function focus(el) {
  el.focus();
}

<Input action={focus} />

This doesn't seem to work for me. I'm trying to do a focus on an input when the modal opens.

What am I doing wrong here?

  <script>
  function focus(el) {
    console.log('focus1',el);  // not working!
    el.focus();
  }
<Section>
  <Modal bind:open={isModalOpen} title={editTag ? 'Edit '+tagName : 'Add '+tagName}>
      <Input bind:this={inputElement} bind:value={newTag} placeholder={tagName} action={focus}/>
      <Button on:click={saveTag}  class="mt-4">{editTag ? 'Save' : 'Add'}</Button>
      <Button on:click={deleteTag}  class="mt-4">Delete</Button>
  </Modal>
</Section>
hardyjosh commented 6 months ago

@TopherTimeMachine this isn't implemented, I was just discussing a possible approach because use wouldn't work without modifying the preprocessor somehow.

TopherTimeMachine commented 6 months ago

@TopherTimeMachine this isn't implemented, I was just discussing a possible approach because use wouldn't work without modifying the preprocessor somehow.

Is there currently any workarounds for making this work? Or what's the best way to get access to the html element?

hardyjosh commented 6 months ago

Is there currently any workarounds for making this work? Or what's the best way to get access to the html element?

No workaround I'm aware of other than making your own component, which is what we did.