# Vue: TypeError: Cannot read properties of undefined (reading 'focus') — template ref accessed before the component is mounted

**Code:** `this.$refs.x / ref.value is undefined or null before mount` · **Category:** Vue · **Seen on:** Vue

A template ref (`ref="input"`) is read before the element exists (setup, created, or before `v-if` renders it).

## Meaning

Template refs are populated after mount. Use them in `onMounted`/`nextTick`, check for null (`inputRef.value?.focus()`), and remember refs inside `v-if`/`v-for` appear later. In `<script setup>` declare `const input = ref(null)` with the same name as the `ref` attribute; with `v-for` refs are arrays.

## Common causes

- Accessing refs in `setup()`/`created`
- Name mismatch between `ref` attribute and variable
- Element under `v-if` not rendered yet
- `v-for` refs are arrays
- Child component refs undefined until mounted

## Quick fix

1. Use `onMounted(() => input.value?.focus())`
2. Match `const input = ref(null)` to `ref="input"`
3. `await nextTick()` after toggling `v-if`

## Detailed fix by platform

### Vue

1. `<input ref="input"><script setup>const input = ref(null); onMounted(() => input.value?.focus());</script>`

## How to diagnose

1. **Timing** — After mount?
2. **Name** — Matches?
3. **v-if** — Rendered?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/vue/vue-template-ref-null-before-mount)
