Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Stimulus Controller in multiple places

I want to be able to use a Stimulus Controller in multiple places in a web app. I want do something like this:

<div data-controller="mycontroller">
  <OneComponent />
</div>

<SomeOtherComponent />

<div data-controller="mycontroller">
  <NewComponent />
</div>

But the controller just seem to connect to the first Component and not in the second. Is it possible to use it as I'm intending to?

Thanks!

like image 458
Rafael Mora Avatar asked Nov 19 '25 12:11

Rafael Mora


1 Answers

Stimulus controllers can be reused. See this sample.

Possible problems that may prevent this from working is if there is a JS error, or that you expect elements in nested components to be used in the parent component, if they have not been rendered yet.

const application = Stimulus.Application.start()

application.register("hello", class extends Stimulus.Controller {
  connect() {
    console.log("connect to", this.element.getAttribute("data-language"))
  }
  
  static get targets() {
    return [ "name" ]
  }
  
  greet() {
    if (this.element.getAttribute("data-language") == "es-ES") {
      console.log(`¡Hola, ${this.nameTarget.value}!`);
    } else {
      console.log(`Hello, ${this.nameTarget.value}!`);
    }
  }
})
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
</head>
<body>
  <div data-controller="hello" data-language="en-US">
    <input data-hello-target="name" type="text" value="John">
    <button data-action="click->hello#greet">Greet</button>
  </div>
  
  <div data-controller="hello" data-language="es-ES">
    <input data-hello-target="name" type="text" value="Jose">
    <button data-action="click->hello#greet">Saudar</button>
  </div>
</body>
</html>
like image 183
Alex Gyoshev Avatar answered Nov 21 '25 10:11

Alex Gyoshev