😘

Svelte(kit)でReact/Preact/tsxが使いたくなったときの対処法

2024/07/07に公開

対処法

$ pnpm add react react-dom
$ pnpm add -D @types/react @types/react-dom

// +page.svelte
<script lang="ts">
  import { onMount } from "svelte";
  import React from "react";
  import ReactDOM from "react-dom/client";
  import Page from "./Page"; // ./Page.tsx
  let container: Element;
  onMount(() => {
    ReactDOM.createRoot(container).render(React.createElement(Page));
  });
</script>

<div bind:this={container}></div>

React.createElementを知らなくて手こずったけど、思ったより簡単にできた

Preact版

Reactはサイズデカすぎ!って場合はPreact
$ pnpm add preact
tsconfig.jsoncompilerOptions.jsxImportSourcepreactにする

// +page.svelte
<script lang="ts">
  import { onMount } from "svelte";
  import { h, render } from "preact";
  import Page from "./Page"; // ./Page.tsx
  let container: Element;
  onMount(() => {
    render(h(Page, null), container);
  });
</script>

<div bind:this={container}></div>

参考:
https://medium.com/@hack2root/react-component-wrapper-for-svelte-f91134733a39
https://stackoverflow.com/questions/56313219/can-i-use-react-components-in-svelte

Discussion