Crate leptos

source
Expand description

§About Leptos

Leptos is a full-stack framework for building web applications in Rust. You can use it to build

  • single-page apps (SPAs) rendered entirely in the browser, using client-side routing and loading or mutating data via async requests to the server.
  • multi-page apps (MPAs) rendered on the server, managing navigation, data, and mutations via web-standard <a> and <form> tags.
  • progressively-enhanced single-page apps that are rendered on the server and then hydrated on the client, enhancing your <a> and <form> navigations and mutations seamlessly when WASM is available.

And you can do all three of these using the same Leptos code.

Take a look at the Leptos Book for a walkthrough of the framework. Join us on our Discord Channel to see what the community is building. Explore our Examples to see Leptos in action.

§Learning by Example

If you want to see what Leptos is capable of, check out the examples:

  • counter is the classic counter example, showing the basics of client-side rendering and reactive DOM updates.
  • counter_without_macros adapts the counter example to use the builder pattern for the UI and avoids other macros, instead showing the code that Leptos generates.
  • counters introduces parent-child communication via contexts, and the <For/> component for efficient keyed list updates.
  • error_boundary shows how to use Result types to handle errors.
  • parent_child shows four different ways a parent component can communicate with a child, including passing a closure, context, and more.
  • fetch introduces Resources, which allow you to integrate arbitrary async code like an HTTP request within your reactive code.
  • router shows how to use Leptos’s nested router to enable client-side navigation and route-specific, reactive data loading.
  • slots shows how to use slots on components.
  • spread shows how the spread syntax can be used to spread data and/or event handlers onto elements.
  • counter_isomorphic shows different methods of interaction with a stateful server, including server functions, server actions, forms, and server-sent events (SSE).
  • todomvc shows the basics of building an isomorphic web app. Both the server and the client import the same app code. The server renders the app directly to an HTML string, and the client hydrates that HTML to make it interactive. You might also want to see how we use Effect::new to serialize JSON to localStorage and reactively call DOM methods on references to elements.
  • hackernews and hackernews_axum integrate calls to a real external REST API, routing, server-side rendering and hydration to create a fully-functional application that works as intended even before WASM has loaded and begun to run.
  • todo_app_sqlite and todo_app_sqlite_axum show how to build a full-stack app using server functions and database connections.
  • tailwind shows how to integrate TailwindCSS with trunk for CSR.

Details on how to run each example can be found in its README.

Here are links to the most important sections of the docs:

§Feature Flags

  • nightly: On nightly Rust, enables the function-call syntax for signal getters and setters.
  • csr Client-side rendering: Generate DOM nodes in the browser.
  • ssr Server-side rendering: Generate an HTML string (typically on the server).
  • hydrate Hydration: use this to add interactivity to an SSRed Leptos app.
  • rkyv In SSR/hydrate mode, uses rkyv to serialize resources and send them from the server to the client.
  • tracing Adds support for tracing.

Important Note: You must enable one of csr, hydrate, or ssr to tell Leptos which mode your app is operating in. You should only enable one of these per build target, i.e., you should not have both hydrate and ssr enabled for your server binary, only ssr.

§A Simple Counter

use leptos::prelude::*;

#[component]
pub fn SimpleCounter(initial_value: i32) -> impl IntoView {
    // create a reactive signal with the initial value
    let (value, set_value) = signal(initial_value);

    // create event handlers for our buttons
    // note that `value` and `set_value` are `Copy`, so it's super easy to move them into closures
    let clear = move |_| set_value.set(0);
    let decrement = move |_| *set_value.write() -= 1;
    let increment = move |_| *set_value.write() += 1;

    view! {
        <div>
            <button on:click=clear>"Clear"</button>
            <button on:click=decrement>"-1"</button>
            <span>"Value: " {value} "!"</span>
            <button on:click=increment>"+1"</button>
        </div>
    }
}

Leptos is easy to use with Trunk (or with a simple wasm-bindgen setup):

use leptos::{mount::mount_to_body, prelude::*};

#[component]
fn SimpleCounter(initial_value: i32) -> impl IntoView {
    // ...
}

pub fn main() {
    mount_to_body(|| view! { <SimpleCounter initial_value=3 /> })
}

Re-exports§

  • pub use tachys::html::event as ev;

Modules§

  • HTML attribute types. Types for HTML attributes.
  • A standard way to wrap functions and closures to pass them to components. Callbacks define a standard way to store functions and closures. They are useful for component properties, because they can be used to define optional callback functions, which generic props don’t support.
  • Types that can be passed as the children prop of a component.
  • Provide and access data along the reactive graph, sharing data without directly passing arguments.
  • Control-flow components like <Show>, <For>, and <Await>.
  • Utilities for working with enumerated types that contain one of 2..n other types.
  • Tools for handling errors.
  • Components used for working with HTML forms, like <ActionForm>.
  • HTML element types. Types for HTML elements.
  • Components to enable server-side rendering and client-side hydration.
  • DOM helpers for Leptos.
  • Utilities for simple isomorphic logging to the console or terminal.
  • MathML element types. Types for MathML.
  • Tools to mount an application to the DOM, or to hydrate it from server-rendered HTML.
  • This module contains the Oco (Owned Clones Once) smart pointer, which is used to store immutable references to values. This is useful for storing, for example, strings.
  • A component that allows rendering a component somewhere else.
  • Exports all the core types of the library.
  • An implementation of a fine-grained reactive system.
  • Server Functions
  • Components to load asynchronous data.
  • SVG element types. Types for SVG.
  • Allows rendering user interfaces based on a statically-typed view tree.
  • Types for reactive string properties for components.

Macros§

  • This behaves like the [view] macro, but loads the view from an external file instead of parsing it inline.
  • Generates a memo into a struct with a default getter.
  • Generates a slice into a struct with a default getter and setter.
  • The template macro behaves like [view], except that it wraps the entire tree in a ViewTemplate. This optimizes creation speed by rendering most of the view into a <template> tag with HTML rendered at compile time, then hydrating it. In exchange, there is a small binary size overhead.
  • The view macro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences:

Traits§

Attribute Macros§

  • Annotates a function so that it can be used with your template as a Leptos <Component/>.
  • Defines a component as an interactive island when you are using the experimental-islands feature of Leptos. Apart from the macro name, the API is the same as the component macro.
  • Declares that a function is a server function. This means that its body will only run on the server, i.e., when the ssr feature on this crate is enabled.
  • Annotates a struct so that it can be used with your Component as a slot.

Derive Macros§

  • Derives a trait that parses a map of string keys and values into a typed data structure, e.g., for route params.