'Why Am I Getting "Target Element Missing" Error?
I'm getting an error in my Rails 6 app because it can't find my data-target, but I don't understand why.
The error in Chrome’s console:
Uncaught Error: Missing target element "channel.messages"
My view:
<div class="col-sm-10" data-controller="channel" data-channel-id="<%= @channel.id %>">
<!-- Chat messages -->
<div class="pr-6 py-4 flex-1">
<div data-target="channel.messages">
<%= render @channel.messages %>
</div>
<div class="pb-6 pr-4 flex-none">
<div class="flex rounded-lg border-2 border-grey overflow-hidden">
<span class="text-3xl text-grey border-r-2 border-grey p-2">
<svg class="fill-current h-6 w-6 block" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M16 10c0 .553-.048 1-.601 1H11v4.399c0 .552-.447.601-1 .601-.553 0-1-.049-1-.601V11H4.601C4.049 11 4 10.553 4 10c0-.553.049-1 .601-1H9V4.601C9 4.048 9.447 4 10 4c.553 0 1 .048 1 .601V9h4.399c.553 0 .601.447.601 1z"/></svg>
</span>
<input type="text" class="w-full px-4" placeholder="Message <%= @other_user.name %>" />
</div>
</div>
</div>
</div>
<%= form_with model: [@channel, Message.new], data: { action: "ajax:success->channel#clearMessage" } do |form| %>
<%= form.text_field :body, class: "form-control", data: { target: "channel.newMessage" } %>
<% end %>
</div>
_messages partial:
<div>
<div class="font-weight-bold"><%= message.user.name %></div>
<div><%= message.body %></div>
</div>
my controller:
import { Controller } from "stimulus"
import consumer from "channels/consumer"
export default class extends Controller {
static targets = [ "messages", "newMessage" ]
connect() {
this.subscription = consumer.subscriptions.create({ channel: "MessageChannel", id: this.data.get("id") }, {
connected: this._connected.bind(this),
disconnected: this._disconnected.bind(this),
received: this._received.bind(this)
})
}
disconnect() {
consumer.subscriptions.remove(this.subscription)
}
_connected() {
}
_disconnected() {
}
_received(data) {
if (data.message) {
this.messagesTarget.insertAdjacentHTML('beforeend', data.message)
}
}
clearMessage(event) {
this.newMessageTarget.value = ''
}
}
When I inspect the HTML, it shows:
<div data-target="channel.messages">
Solution 1:[1]
The issue with my code was that the data-controller had to be in the parent element.
Initially it was located inside the form and it wasn't working properly. After I moved the data-controller inside the parent tag everything was fine.
Solution 2:[2]
The problem here is the data-target attribut. You need to use:
data-channel-target
The definiion shows this structure:
data-yourcontroller-target
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 | Dharman |
