Use Svelte components in React.
npm install @baykar/svelte2reactGiven 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).
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:
-
Calling
setNametriggers a re-render ofApp. -
WrappedSvelteButtonis re-rendered because its parent (App) re-rendered -
pStoreRef.current.set(p)is called in index.ts.pStoreRef.currentis a Svelte store that stores the props forSvelteButton. -
pStoreRef.currentcalles its only subscriber, which is an instance of the Svelte componentWrapper, defined in Wrapper.svelte. -
Wrapperupdates the props passed to your component due to{...$pState}in Wrapper.svelte. ($pStateis whyWrapperautomatically subscribes topStoreRef.currentpreviously.)
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>