It doesn't need to be that hard.
How you can get to speed with WASM as fast as possible as a TypeScript Developer by showcasing comparable examples between React and Yew.
Rust's Web Assembly Concepts for TypeScript Developers
This contains a dual-runnable project which allows you to see React and Yew code side by side.
This project is fully bootable and can be accessed by running:
- Install pnpm.
- Run
pnpm install
. - Run
pnpm dev
(To Launch the dev server) - Run
pnpm tailwind
(To launch Tailwind)
cargo install trunk
- Install bonnie
cargo install bonnie
- Run
trunk serve
. - Visit
http://localhost:8080
- Run
pnpm tailwind
(To launch Tailwind)
cargo install bonnie
- Install dioxus cli
cargo install dioxus-cli
- Add
wasm32-unknown-unknown
:
rustup target add wasm32-unknown-unknown
- Add Dioxus
cargo add dioxus dioxus-web
You will now be able to see the same project running in both React and Yew.
Everything is inside the source folder. Things may get funny if you try running both the Yew project and React.
- Do not use this project structure or naming convention as an example for your Rust WASM or TypeScript project.
- It was intentionally done to showcase the parity between the two approaches.
- Trunk will get into an infinite loop if you have
trunk serve
running while editing.ts
and.tsx
files. - Folders follow Rust's snake case convention as the built-in linter will return warnings.
If you've seen there's a piece of code that we can improve, by all means!
How would you do something in React TypeScript vs Yew Rust.
- Conditional Rendering:
import type { FunctionComponent } from "react";
export type ConditionalRenderingProps = {
variant: "primary" | "secondary";
};
export const ConditionalRendering: FunctionComponent<
ConditionalRenderingProps
> = (props) => {
return (
<>
{props.variant === "primary" && <p>Primary</p>}
{props.variant === "secondary" && <p>Secondary</p>}
</>
);
};
use yew::prelude::*;
#[derive(Clone, PartialEq)]
pub enum ConditionalVariant {
Primary,
Secondary,
}
#[derive(Properties, Clone, PartialEq)]
pub struct ConditionalRenderingProps {
pub variant: ConditionalVariant,
}
#[function_component(ConditionalRendering)]
pub fn conditional_rendering(props: &ConditionalRenderingProps) -> Html {
let variant = &props.variant;
html! {
<div>
{
match variant {
ConditionalVariant::Primary => html! {
<p>{"Primary"}</p>
},
ConditionalVariant::Secondary => html! {
<p>{"Secondary"}</p>
},
}
}
</div>
}
}