Skip to content

canbaykar/svelte2react

Repository files navigation

svelte2react

Use Svelte components in React.

Install

npm install @baykar/svelte2react

Usage

Given an example Svelte component such as;

<!-- SvelteButton.svelte -->
<script lang="ts">
    let { name = '' } = $props();
    let count = $state(0);
    console.log('Svelte component initialized');
</script>

<button onclick={() => count++}>
    Hi {name}! You clicked me {count} times!
</button>

You can use it in a React component like:

import { useState } from 'react';

import { Wrap } from '@baykar/svelte2react';
import SvelteButton from './SvelteButton.svelte';
const WrappedSvelteButton = Wrap(SvelteButton);

export default function App() {
  const [name, setName] = useState('Mark');

  return <>
    <label>
      Your name:
      <input
        value={name}
        onChange={e => setName(e.target.value)}
      />
    </label>

    My Svelte component:
    <WrappedSvelteButton name={name} />
  </>;
}

Now the rendered SvelteButton will react to changes to name (without re-initializing everytime name changes).

Prop Reactivity Breakdown

The Svelte component given to Wrap is wrapped in a Svelte component (defined in Wrapper.svelte) and a React component (defined in index.ts). These two communicate via a Svelte store pStoreRef.current that stores your components props.

In the example above, once setName is called:

  1. Calling setName triggers a re-render of App.

  2. WrappedSvelteButton is re-rendered because its parent (App) re-rendered

  3. pStoreRef.current.set(p) is called in index.ts. pStoreRef.current is a Svelte store that stores the props for SvelteButton.

  4. pStoreRef.current calles its only subscriber, which is an instance of the Svelte component Wrapper, defined in Wrapper.svelte.

  5. Wrapper updates the props passed to your component due to {...$pState} in Wrapper.svelte. ($pState is why Wrapper automatically subscribes to pStoreRef.current previously.)

Caveats

Some Svelte and React features obviously won't make sense or won't work. To name some:

  • ❌ Children

    <WrappedSvelteComponent>
      <SvelteOrReactComponent />
    </WrappedSvelteComponent>
  • ❌ Svelte bindings

    <script lang="ts">
      let { value = $bindable(), ...props } = $props();
    </script>

About

Use Svelte components in React.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors