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
- is this even a good approach ?
- 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
Basically your approach should work. I'd suggest the following:
--> 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:
For the start I recommend to add a connect-Method to make sure that your controller is loading correctly: