Stack Exchange
why template ref is null?
Hi I have a ref called messageRef on a paragraph (inside a v-for loop) in order to add autofocus on the element when is edited, but the ref is null when I try to edit it?
My html template, where I assign the ref:
 <p
    v-if="textMessage.imageType"
    ref="messageRef"
    :contenteditable="textMessage.editable"
    :class="`${textMessage.from === 'therapist' ? 'bg-brand-blue text-white' : 'bg-brand-light-gray text-brand-dark-green' } message p-4 my-3 w-fit rounded-2xl text-sm max-w-prose`"
 >
    <img
      class="max-w-xs"
      :src="textMessage.text"
    >
</p>

and the script part
setup() {
    const messageRef = ref(null)
    const editMessage = () => {
      // eslint-disable-next-line no-shadow
      messages.value.forEach((message, index) => {
        if (message.id === activeMessageId.value) {
          messages.value[index].editable = true
          messageRef.value.focus()
        }
      })
    }
  return { messageRef, editMessage}
}

Can someone spot the issue?

I think you are missing a :. Now you are referencing the static string "messageRef", but looks like you want the actual messageRef from setup.
Try changing to:
:ref="messageRef"


it is still null with this change

I forgot to mention that this is inside a v-for loop
