consider the rails view bellow:
<div
data-controller='manager'
data-manager-target='inputcontainer'
>
<input
class='hidden'
type='text'
data-manager-target='input'
>
</div>
<div
data-manager-target='label'
data-action='dblclick->manager#show'
>
double click to show input
</div>
and this code in the manager_controller.js
:
show() {
this.inputcontainerTarget.classList.remove('hidden');
this.inputTarget.focus();
}
When I double click the second div
to show the first one I get the error Uncaught TypeError: self.inputTarget is undefined
.
I understand why it's happening but I'm struggling to find a way to make it work.
Does anybody know how can I make it work?
This is a Ruby on Rails 7.1 app and I'm using Stimulus to wire up the front-end and Tailwind for styling.
<div data-controller="manager">
<input class="hidden" type="text" data-manager-target="input">
<!-- this needs to be inside the `data-controller` div -->
<div data-action="dblclick->manager#show">
double click to show input
</div>
</div>
// app/javascript/controllers/manager_controller.js
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="manager"
export default class extends Controller {
// NOTE: you have to declare your targets
// this is for `data-manager-target="input"`
static targets = ["input"];
show() {
this.inputTarget.classList.remove("hidden");
this.inputTarget.focus();
}
}
Note, there is no need for data-manager-target="inputcontainer"
on data-controller="manager"
element, you can refer to controller element itself with this.element
.