Rails Stimulus two data targets

138 views Asked by At

so im experimenting and learning Rails Stimulus and the idea i want to realise is that i have two modal forms ( one for login and second for registration ) my view:

<div data-controller="modal">

  <button data-action="click->modal#login" data-target="loginForm" class="flex items-center">
   Login
  </button>

  <div data-modal-target="loginForm" class="relative z-10 hidden">
    <%= render 'layouts/modal_login' %>
  </div>

  <div data-modal-target="registerForm" class="relative z-10 hidden">
    <%= render 'layouts/modal_register' %>
  </div>

</div>

and inside login and register partials i want to add button to switch between modal forms example from modal_login:

<button data-action="click->modal#register" class="flex items-center">
  Register
</button>

and my stimulus modal_controller.js:

export default class extends Controller {
  static targets = ['loginForm', 'registerForm'];

  login() {
    console.log("login");
    this.loginFormTarget.classList.toggle("hidden");
  }

  register() {
    console.log("register");
    this.loginFormTarget.classList.toggle('hidden');
    this.registerFormTarget.classList.toggle('hidden');
  }
}

Question

  1. is this even a good approach ?
  2. why when i try to call data-action register from login partial i get:
Error invoking action "click->modal#register"

Error: Missing target element "registerForm" for "modal" controller

i expected that when i press register button the login modal will hide and register modal form will be displayed

1

There are 1 answers

0
zaphodbln_ On BEST ANSWER

Basically your approach should work. I'd suggest the following:

<button data-action="click->modal#login" data-target="loginForm" class="flex items-center">
   Login
</button>

--> You should omit "data-target="loginForm"". I guess it's a missunderstanding. Data-Target ist not the target of the action (you want to toggle the loginForm), but simply an identifier of the element (in this case the button).

Perhaps you have a second registerForm-Target in on of your partials - please check and delete, too.

Secondly you should add a parameter to your JS-Methods like this:

login(event) {
   ...   
}

register(event) {
    ...
}

For the start I recommend to add a connect-Method to make sure that your controller is loading correctly:

connect(){
  console.log("Controller connected")
}