Using Sveltris to build interoperable React and Svelte
Published: 2023-12-29 05:55:50

There are new ways for web developers to boost the flexibility and efficiency of their workflows. Sveltris is one such experimental
framework for developing interoperable apps that is gaining popularity.

in this article, we will delve into the world of Sveltris, examining its purpose, features, and benefits, as well as the advantages and
disadvantages of using various frameworks in a single project.

## What is Sveltris?
Sveltris is a complex library that allows for the smooth integration of Svelte components into React projects. This breakthrough technology fusion enables developers to exploit the best features of both Svelte and React, resulting in a harmonious synergy that improves performance and expands the React ecosystem.

At its core, Svelte, known for its remarkable runtime efficiency, enables the building of highly performant components via its compiled methodology, which shifts the heavy lifting from the client to build time. React, on the other hand, has a plethora of tools, frameworks, and community resources that serve as the foundation of modern web development.

## Why use Sveltris?

By using Sveltris, developers gain the ability to combine the unparalleled performance gains of Svelte's compilation process with the robustness of React's ecosystem. This combination provides an unparalleled development experience, as developers can craft components using Svelte's elegant syntax and then easily integrate them into React applications.

Svelte is an extremely performant framework, and Sveltris adds no overhead. This means you may get the same Svelte performance benefits in your React apps.

Sveltris also supports server-side rendering (SSR) out of the box, with no further configuration required. This ensures that components operate well in SSR contexts, increasing the versatility and compatibility of Sveltris applications.

React has a vast and active ecosystem, and there are numerous libraries and tools available to you. Sveltris allows you to use these libraries and tools alongside Svelte components, giving you the best of both worlds.

With Sveltris, you can intermix UI primitives like components and state primitives like hooks between frameworks without even noticing. It is simple to use. If you know how to use Svelte, you'll have no trouble using Sveltris.

In addition, when working with teams comprised of members with competence in either React or Svelte, Sveltris improves teamwork. You can construct features in your choice framework and seamlessly connect them with Sveltris, resulting in a more flexible and efficient development process.



## Getting started with Sveltris
The combination of the two frameworks guarantees that the finished application benefits from both the runtime efficiency of Svelte and the broad toolset of React, which can be built either on Esbuild, Vite, and Webpack. In this tutorial, we'll be using [Vite](https://vitejs.dev/guide/).


## Creating a Svelte-in-React application
We'll begin with creating a svelte in react app. Run the following command to kick start:
```
npm create vite@latest sveltris-react -- --template react
OR
yarn create vite sveltris-react  --template react
```
Next, navigate to the app directory and install the default dependencies. Like the code below:

```
cd sveltris-react
npm install
```
After that, run the following command to install Sveltris and the Svelte Vite plugin as a dev dependency:
```
npm install sveltris
npm install --save-dev @sveltejs/vite-plugin-svelte
```
To start the app run the code below:
```
npm run dev
```
If you follow the process very well, you should have your sveltris software successfully installed. Finally, update the `vite.config.js` file with the code below:
```javascript
// vite.config.js
import { sveltrisVitePlugins } from "sveltris"
import { defineConfig } from 'vite';
 
export default defineConfig({
  plugins: [
    ...sveltrisVitePlugins()
  ]
})
```
We can now develop Svelte components and use them in our React application.
To begin, create a new Hello.svelte file in the default /src directory and paste the following code into it: `hello.svelte`
```javascript
    // src/hello.svelte
<div>
        <h1>Hello Svelte</h1>
    </div>
    <style>
        h1{
            border: 5px solid #121110;
            padding: 20px;
        }
    </style>
```

Next, create a file `welcome.svelte` in your source directory and paste the following code: 
```javascript
// src/welcome.svelte
<div>
    <h2>Welcome to Svelte</h2>
</div>
<style>
    h2{
        border: 5px solid #121110;
        padding: 20px;
    }
</style>
```

After that, replace the `src/app/jsx` file with the following code:
```javascrit
import Hello from "./Hello.svelte?in-react";
import Welcome from "./welcome.svelte?in-react";

function App() {
  return (
    <>
      <Hello />
      <Welcome />
      <h1
        style={{
          padding: " 20px",
          border: "2px solid #bc9aed",
        }}
      >
        greetings with React!
      </h1>
    </>
  );
}

export default App;

```
The code above integrates Svelte components into a React application. It imports two Svelte components with a React-specific query parameter, and then renders those components alongside a styled React-specific `<h1>` element using the App component, which is the main entry point for the React app.
This is the output from the code above: 
![](https://hackmd.io/_uploads/rkFDgbh2h.png)

### Working with Slot and Children
As the children provided to these components, the default slot of the underlying Svelte component is set. We'll import a Svelte component called "Layout.svelte," and during the import, we'll add a query as a parameter in-react. Like the code below:

```javascript
import Layout from './Layout.svelte?in-react';
 
<Layout>
  <h1>Hello world</h1>
</Layout>;
```
This indicates that a specific interaction or compatibility with React is being evaluated.

## Creating a React-in-Svelte application
For us to create react in svelte, we have to go through the installation process again, but we'll be using the react plugin instead. just follow as we continue:
```
npm create vite@latest sveltris-svelte -- --template svelte
cd sveltris-svelte && npm install

Next

npm install sveltris
npm install --save-dev @vitejs/plugin-react
```
Now Let's update our `vite.config.js` file with the code below:
```javascript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { sveltrisVitePlugins } from "sveltris";
import { svelte } from "@sveltejs/vite-plugin-svelte";

export default defineConfig({
  plugins: [svelte(), react(), ...sveltrisVitePlugins()],
});
```
We are done with the installation process. Next, let's create a file in your src directory with the following codes on them. Our first file is `tab.jsx`:

```javascript
export default function Tab(title, content) {
  return (
    <div style={{ border: "3px solid #bc9aed", borderRadius: "5px", padding: "10px" }}>
      <h1>{title}</h1>
      <p>{content}</p>
    </div>
  );
}
```
This code defines a reusable Tab component with a border, rounded corners, and padding. The title and content variables allow dynamic data insertion into the component, making it flexible for displaying varied content within the styled container.

Next, open the default src/App.svelte file and change its content with the following code:
```javascript
<script>
  import Card from './Tab.jsx?in-svelte';
</script>

<main style="border: 3px solid #FFC107;padding: 25px;">
  <h1>Svelte App</h1>
  <Tab title="React Card" content="Card component created with React and imported to a Svelte app." />
</main>
```
From the code above, We imported and displayed the previously developed component within our Svelte application. When you launch the program, you should see something like the following:

![](https://hackmd.io/_uploads/ByLkm2332.png)

### Working with react Hooks 
Sveltris unifies the use of React hooks within Svelte components via the wrapper. This wrapper allows you to interact with React hooks while also taking advantage of Svelte's reactive architecture by returning a read-only store that can be subscribed to by your Svelte components. This integration enhances your development experience by combining the strengths of both frameworks.

**Subscribing to the Store:** The Svelte store returned by the use function is reactive. This indicates that your Svelte component can receive updates from this store. When the value of the store changes as a result of interactions with React hooks, your Svelte component can immediately react and update.

Here is example code:
```javascript
<script>
import { useState } from 'react'
import { use } from 'sveltris/svelte'
 
const counter = use(() => useState(0))
</script>
 
{#if $counter}
  {@const [count, setCount] = $counter}
  <button on:click={() => setCount(c => c + 1)}>
    {count}
  </button>
{/if}
```
From the above code, we use the useState hook to initialize a counter state, bind the state and setter to Svelte variables, and render a button that increments the counter when clicked, all while seamlessly merging React and Svelte concepts with the help of Sveltris. Here is the output:
 ![](https://hackmd.io/_uploads/H1vhsn223.gif)
 
 ## Building an interoperable social app with Sveltris
The convergence of Svelte and React, facilitated by the emerging concept of "Sveltris," presents an exciting opportunity to build a truly interoperable social media dashboard. This dashboard combines the reactive power of Svelte with the extensive ecosystem of React components, offering developers a novel approach to crafting comprehensive and feature-rich user interfaces.
 
We're using Sveltris to design an interoperable social media dashboard that includes Svelte and React components. We'll also make use of third-party packages from these libraries.

To display the bar chart and add a new post, we'll use the react-apexcharts package and the svelte-svoast package, respectively. Also, to avoid mistakes, make sure you thoroughly follow the method. Now, let us install the packages required to develop our application. 

NB: We are expanding on the previous section's Svelte-in-React app.


```
yarn add react-apexcharts apexcharts svoast
or 
npm install react-apexcharts apexcharts svoast
```
The command above will install both react-apexcharts svelte-svoast libraries.

Next, paste the following code below in your `src/index.css` file to give the necessary style to your application:

```css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Polysans, sans-serif;
}

main .header {
  text-align: center;
  margin: 10px 0;
}

.container {
  display: flex;
  justify-content: space-between;
  padding: 40px;
  height: 87vh;
}

.first-row {
  border: 3px solid #1a50e6;
  padding: 40px;
  width: 45%;
  height: 100%;
  overflow: auto;
}

.add-btn {
  cursor: pointer;
  font-size: 12px;
  padding: 10px 10px;
  margin-top: 10px;
  background-color: rgb(23, 57, 47);
  color: white;
  border: none;
  border-radius: 5px;
}
.add-btn:hover {
  background-color: rgb(44, 215, 166);
  color: black;
}
.posts-wrapper {
  margin-top: 40px;
}

.post-card {
  padding: 20px;
  border-radius: 5px;
  border: 2px solid #368be0;
  margin-bottom: 20px;
}

.post-card p {
  margin: 20px 0;
  color: #393e43;
}

.post-card img {
  max-width: 100%;
  border-radius: 5px;
}

.sec-row {
  border: 3px solid #51dc6d;
  padding: 40px;
  width: 50%;
}

```

## Creating post cards and toast notifications
The toast and card notifications Contribute to improving the user experience in both scenarios by providing clear and succinct ways to deliver information and connect with users. They are critical tools for modern application design because they enable effective communication while retaining a visually appealing and user-friendly interface.

First, create a file named PostCard.svelte inside the src/ folder and paste the code below:
```javascript
<script>
  export let id, author, content;
</script>

<div class="post-card">
  <h4>{author}</h4>
  <p>{content}</p>
  <img src={"https://source.unsplash.com/random/?beach," + id} alt="" />
</div>
```
The code above displays information about a post, such as the author's name, the content text, and an image that was dynamically obtained. Reactive updates from Svelte enable dynamic content modification based on values given to the component.

Next, create a file named `Toast.svelte` and paste the following code:
```javascript
<script>
  export let showToast, toastMessage;
  import { Toasts, toast } from "svoast";

  $: if (showToast) {
    launchToast();
  }

  async function launchToast() {
    toast.success(toastMessage);
  }
</script>

<Toasts position="top-left" />
```
From the code above, the Svelte component handles the display of toast notifications. When **showToast** becomes true, the **launchToast** function is triggered. The `toast.success()` method from the "svoast" library is used to display a success toast notification with the message specified in toastMessage. The `<Toasts>` component is used to render and manage the toast notifications, with its position set to top-left.

## Listing and adding random posts
To list and add random posts, replace the code below in the `src/App.jsx` file:


```javascript
import React, { useState } from "react";
import Chart from "react-apexcharts";
import Toast from "./Toast.svelte?in-react";
import PostCard from "./PostCard.svelte?in-react";

const initialPosts = [
  {
    author: "Sam Tems",
    content: "Hi! Setting up my Otter account!",
  },
  {
    author: "John Tems",
    content: "Hello, Setting up teta account",
  },
];

const getPostCount = (posts, author) => {
  return posts.filter((post) => post.author === author).length;
};

const App = () => {
  const [posts, setPosts] = useState(initialPosts);
  const [showToast, setShowToast] = useState(false);

  const addRandPost = () => {
    const randPost = posts[Math.floor(Math.random() * posts.length)];
    const updatedPosts = [...posts, randPost];
    setPosts(updatedPosts);
    setShowToast(true);
  };

  return (
    <>
      <Toast showToast={showToast} toastMessage="New post added successfully!" />
      <main>
        <div className="header">
          <h1>Teta 🦦</h1>
          <button className="add-btn" onClick={addRandPost}>
            Add Random Post
          </button>
        </div>
        <div className="container">
          <div className="first-row">
            <div className="posts-wrapper">
              {posts.map((post, id) => (
                <React.Fragment key={id}>
                  <PostCard id={id} author={post.author} content={post.content} />
                </React.Fragment>
              ))}
            </div>
          </div>
        </div>
      </main>
    </>
  );
};

export default App;
```
Let's get an understanding of what each of the functions and code does from the code above:

* **Import Statements**: imports React, the useState hook, and the Chart component from "react-apexcharts." Additionally, the Svelte components Toast and PostCard are imported using the React-specific query option "?in-react."

* **Initial Data**: An initialPosts array holds a collection of sample posts with author and content.

* **getPostCount Function**: This function figures out how many posts have been made by a particular author.

* **App Component**: The primary App component manages posts and toast display state using React's useState hook.

* **addRandPost Function**: This function updates the state and sends a toast notification when it adds a random post from the list of posts.

* **Return Statement**:The component renders a toast notification using the Toast Svelte component and delivers JSX along with a header section and a button to add random posts. svelte PostCard.

We are Partially done with the app. Here is the output of the first stage of our Sveltris application

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ugahnjvz9kxz0fmc1sp1.gif)




## Visualizing post counts with a bar chart
We're going to add some code to the `App.jsx` file to create a bar chart showing how many posts each user has made.

Create a new state called chartData and fill it with the following default information:

```javascript
const [chartData, setChartData] = useState(() => {
  const samPostsCount = getPostCount(posts, "Sam Tems");
  const johnPostsCount = getPostCount(posts, "John Tems");

  return {
    options: {
      chart: {
        id: "basic-bar",
      },
      xaxis: {
        categories: ["no of posts"],
      },
    },
    series: [
      { name: "Sam", data: [samPostsCount] },
      { name: "John", data: [johnPostsCount] },
    ],
  };
});
```
The code above uses React's useState hook to initialize and manage the state of a chartData object. The object holds the necessary data for rendering a bar chart, including chart options and series data based on calculated post counts. This setup enables the dynamic rendering of the chart as the post data changes.

To automatically update the chart data whenever a new post is made, modify the addRandPost() code with  the code below:
```javascript
const addRandPost = () => {
  const randPost = posts[Math.floor(Math.random() * posts.length)];
  const updatedPosts = [...posts, randPost];
  setPosts(updatedPosts);

  setChartData((prevChartData) => {
    const samPostsCount = getPostCount(updatedPosts, "Sam Tems");
    const johnPostsCount = getPostCount(updatedPosts, "John Tems");

    return {
      ...prevChartData,
      series: [
        { name: "Sam", data: [samPostsCount] },
        { name: "John", data: [johnPostsCount] },
      ],
    };
  });

  setShowToast(true);
};
```

Finally, modify the JSX code to display the bar chart using the chartData:
```javascript
<div className="container">
  <div className="first-row">
    {/* ... */}
  </div>
  <div className="sec-row">
    <h3>Post Trends</h3>
    <Chart
      options={chartData.options}
      series={chartData.series}
      type="bar"
      width="500"
    />
  </div>
</div>
```

If you follow this tutorial, You should have the following output display on your screen


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6nld00edfg7g393xehy.gif)

This app illustrates the potency of Sveltris by merging React and Svelte to construct potent applications.

We fashioned the Toast and PostCard components with Svelte, and for the Toast element, we utilized an external Svelte component. Moreover, within our App.jsx file, we also highlighted Svelte's capability to exchange responsive data between Svelte and React, underscoring Svelte's remarkable adaptability across frameworks.

## Conclusion
Harnessing the capabilities of Sveltris to construct interoperable applications that seamlessly integrate React and Svelte brings forth a new realm of possibilities for modern web development. By combining the strengths of these two frameworks, developers can create versatile and dynamic user interfaces that leverage the unique features of each technology.

In this process, we've demonstrated how to create components that bridge the gap between React and Svelte, showcasing Svelte's remarkable compatibility and flexibility. As we've explored the seamless integration of functionalities such as toast notifications, post cards, and data sharing, it becomes evident that Sveltris is a powerful tool for promoting collaboration between React and Svelte, transforming them into complementary technologies rather than isolated choices.