Using Third-Party Stimulus Components

In the last topic, we explained how to use the Symfony Stimulus Bundle with AssetMapper. Now, let's learn how to use third-party Stimulus components.

Stimulus is widely used outside of Symfony, so many pre-made controllers exist. You can use them without writing any backend code.

Popular sources:

  • stimulus-components – A large number of pre-made Stimulus controllers, like for Copying to clipboard, Sortable, Popover (similar to tooltips) and much more.
  • stimulus-use – Add composable behaviors to your Stimulus controllers, like debouncing, detecting outside clicks and many other things.
  • stimulus-library – An extensive library of stimulus controllers for all use cases

We start with JavaScript-only examples that do not require any backend code.

1. Install a Third-Party Stimulus Controller

Example: Install a Clipboard Controller

php bin/console importmap:require @stimulus-components/clipboard

Example: Install Stimulus Library

php bin/console importmap:require stimulus-library

After requiring, the package is downloaded and available for import in JS.

2. Modify assets/stimulus_bootstrap.js

This is where you register external controllers.

import { startStimulusApp } from '@symfony/stimulus-bundle';

// Start Stimulus app
const app = startStimulusApp();

// ---------------------------------------------
//   Third-party Stimulus controllers
// ---------------------------------------------

// stimulus-components
import Clipboard from '@stimulus-components/clipboard';

// stimulus-library
import { AutosizeController } from 'stimulus-library';

// Register them
app.register('clipboard', Clipboard);
app.register('autosize', AutosizeController);

3. Use the Controllers in HTML

Example A — Copy to Clipboard (stimulus-components)

<div data-controller="clipboard" data-clipboard-success-content-value="Copied!">
    <input type="text" value="Hello" data-clipboard-target="source">

    <button type="button" data-action="clipboard#copy" data-clipboard-target="button">
        Copy
    </button>
</div>

Example B — Autosize Textarea (stimulus-library)

<textarea
    data-controller="autosize"
    placeholder="Type something..."
></textarea>
  • Clipboard automatically copies the text to the clipboard.
  • AutosizeController automatically resizes the <textarea> as the user types.
  • No extra backend code is required.

Next Up

In the next topic, we will explore server-backed Stimulus components, like autocomplete inputs, that fetch data from Symfony routes or entity autocompleters.

1 Like