DEV Community

Ryan John
Ryan John

Posted on • Originally published at vureact.top

How does VuReact compile Vue 3's useTemplateRef() to React?

VuReact is a compiler toolchain for migrating from Vue to React — and for writing React with Vue 3 syntax.

In this article, we will look at how Vue 3's useTemplateRef() API is mapped into React.

Before We Start

To keep the examples easy to read, this article follows two simple conventions:

  1. All Vue and React snippets focus on core logic only, with full component wrappers and unrelated configuration omitted.
  2. The discussion assumes you are already familiar with the API shape and core behavior of Vue 3 useTemplateRef().

Compilation Mapping

Vue useTemplateRef() -> React useRef() + .current

useTemplateRef() is Vue 3's API for accessing template refs. React does not have a directly equivalent runtime API with the same name, but the semantics map naturally to useRef().

VuReact compiles useTemplateRef() into useRef(), and rewrites .value access into .current.

  • Vue
<script setup lang="ts">
import { onMounted, useTemplateRef } from 'vue';

const pRef = useTemplateRef<HTMLParagraphElement>('p');

onMounted(() => {
  console.log(pRef.value.offsetWidth);
});
</script>
Enter fullscreen mode Exit fullscreen mode
  • Compiled React
import { useRef } from 'react';
import { useMounted } from '@vureact/runtime-core';

const pRef = useRef<HTMLParagraphElement | null>(null);

useMounted(() => {
  console.log(pRef.current?.offsetWidth);
});
Enter fullscreen mode Exit fullscreen mode

As the example shows, Vue useTemplateRef() maps directly to React useRef().

VuReact preserves the template ref type information and rewrites access from pRef.value to pRef.current, keeping the original intent intact.

Template refs in Vue templates -> React ref bindings

When a Vue template uses ref to capture a DOM node, VuReact compiles that pattern into React's ref={...} binding.

  • Vue
<template>
  <p ref="pRef">Hello</p>
</template>

<script setup lang="ts">
import { useTemplateRef } from 'vue';

const pRef = useTemplateRef<HTMLParagraphElement>('p');
</script>
Enter fullscreen mode Exit fullscreen mode
  • Compiled React
import { useRef } from 'react';

const pRef = useRef<HTMLParagraphElement | null>(null);

return <p ref={pRef}>Hello</p>;
Enter fullscreen mode Exit fullscreen mode

VuReact converts Vue's template ref binding into React's native ref binding syntax while keeping the type and access model consistent.

Related Links

Top comments (0)