Use react component in svelte5
Import and use react component library in svelet5, sample project address: /shenshouer/my-svelte-react
There is still a problem in svelte5, and children cannot be passed to react to render
Create a project using svletkit
$ npx sv create my-svelte-react % npx sv create my-svelte-react ┌ Welcome to the Svelte CLI! (v0.6.10) │ ◇ Which template would you like? │ SvelteKit minimal │ ◇ Add type checking with Typescript? │ Yes, using Typescript syntax │ ◆ Project created │ ◇ What would you like to add to your project? (use arrow keys / space bar) │ none │ ◇ Which package manager do you want to install dependencies with? │ pnpm │ ◆ Successfully installed dependencies │ ◇ Project next steps ─────────────────────────────────────────────────────╮ │ │ │ 1: cd my-svelte-react │ │ 2: git init && git add -A && git commit -m "Initial commit" (optional) │ │ 3: pnpm run dev --open │ │ │ │ To close the dev server, hit Ctrl-C │ │ │ │ Stuck? Visit us at /chat │ │ │ ├──────────────────────────────────────────────────────────────────────────╯ │ └ You're all set! $ cd my-svelte-react $ pnpm install $ pnpm dev
Install react-related dependencies
$ pnpm i react react-dom $ pnpm i --save-dev @types/react @types/react-dom $ pnpm add @vitejs/plugin-react -D
Modify and add react support
import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; # <---- here export default defineConfig({ plugins: [sveltekit(), react()] # <---- here });
Create react svelte adapter, the code is as follows:
# src/lib/utils/ <script lang="ts"> import React from "react"; import ReactDOM from "react-dom/client"; import { onDestroy, onMount } from "svelte"; const e = ; let container: HTMLElement; let root: ; onMount(() => { const { el, children, class: _, ...props } = $$props; try { root = (container); (e(el, props, children)); } catch (err) { (`react-adapter failed to mount.`, { err }); } }); onDestroy(() => { try { if (root) { (); } } catch (err) { (`react-adapter failed to unmount.`, { err }); } }); </script> <div bind:this={container} class={$$}></div>
Currently there is a problem with this part of the adapter, children cannot be retrieved and rendered in react component
refer to:
props-and-restProps
issues
Add react component library, such asant design
$ pnpm add antd # + <script lang="ts"> import { Button } from "antd"; import ReactAdapter from "$lib/utils/"; </script> <ReactAdapter el={Button} type="primary">Hello, World!</ReactAdapter>
This is the end of this article about using react components in svelte5. For more related content on using react components in svelte5, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!