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§

attr
HTML attribute types. Types for HTML attributes.
attribute_interceptor
Wrapper for intercepting component attributes.
callback
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.
children
Types that can be passed as the children prop of a component.
config
context
Provide and access data along the reactive graph, sharing data without directly passing arguments.
control_flow
Control-flow components like <Show>, <For>, and <Await>.
either
Utilities for working with enumerated types that contain one of 2..n other types.
error
Tools for handling errors.
form
Components used for working with HTML forms, like <ActionForm>.
html
HTML element types. Types for HTML elements.
hydration
Components to enable server-side rendering and client-side hydration.
leptos_dom
DOM helpers for Leptos.
logging
Utilities for simple isomorphic logging to the console or terminal.
math
MathML element types. Types for MathML.
mount
Tools to mount an application to the DOM, or to hydrate it from server-rendered HTML.
oco
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.
portal
A component that allows rendering a component somewhere else.
prelude
Exports all the core types of the library.
reactive
An implementation of a fine-grained reactive system.
server
Utilities for communicating between the server and the client with Leptos.
server_fn
Server Functions
suspense
Components to load asynchronous data.
svg
SVG element types. Types for SVG.
tachys
Allows rendering user interfaces based on a statically-typed view tree.
task
Utilities for working with asynchronous tasks.
text_prop
Types for reactive string properties for components.

Macros§

include_view
This behaves like the view macro, but loads the view from an external file instead of parsing it inline.
memo
Generates a memo into a struct with a default getter.
slice
Generates a slice into a struct with a default getter and setter.
template
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.
view
The view macro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences:

Traits§

IntoView
A trait that is implemented for types that can be rendered.

Attribute Macros§

component
Annotates a function so that it can be used with your template as a Leptos <Component/>.
island
Defines a component as an interactive island when you are using the islands feature of Leptos. Apart from the macro name, the API is the same as the component macro.
lazy
The #[lazy] macro marks an async function as a function that can be lazy-loaded from a separate (WebAssembly) binary.
server
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.
slot
Annotates a struct so that it can be used with your Component as a slot.

Derive Macros§

Params
Derives a trait that parses a map of string keys and values into a typed data structure, e.g., for route params.
","&[u8]":"

Notable traits for &[u8]

impl Read for &[u8]
","&mut as Index>::Output":"

Notable traits for Vec<u8, A>

impl<A> Write for Vec<u8, A>
where\n A: Allocator,
"," T + Send>> as ReactiveFunction>::Output":"

Notable traits for Arc<File>

impl Read for Arc<File>
impl Write for Arc<File>
"," as IntoDirective<(Element,), ()>>::Cloneable":"

Notable traits for Arc<File>

impl Read for Arc<File>
impl Write for Arc<File>
"," as IntoDirective<(Element, P), P>>::Cloneable":"

Notable traits for Arc<File>

impl Read for Arc<File>
impl Write for Arc<File>
"," as AddAnyAttr>::Output":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as Attribute>::AsyncOutput":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as Attribute>::Cloneable":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as Attribute>::CloneableOwned":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as Attribute>::State":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as NextAttribute>::Output":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as Render>::State":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as RenderHtml>::AsyncOutput":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"," as IntoIterator>::IntoIter":"

Notable traits for Vec<u8, A>

impl<A> Write for Vec<u8, A>
where\n A: Allocator,
"," as AddAnyAttr>::Output":"

Notable traits for Vec<u8, A>

impl<A> Write for Vec<u8, A>
where\n A: Allocator,
"," as IntoDeserializer<'de, E>>::Deserializer":"

Notable traits for Vec<u8, A>

impl<A> Write for Vec<u8, A>
where\n A: Allocator,
"," as IntoWasmAbi>::Abi":"

Notable traits for Vec<u8, A>

impl<A> Write for Vec<u8, A>
where\n A: Allocator,
"," as Render>::State":"

Notable traits for Vec<u8, A>

impl<A> Write for Vec<u8, A>
where\n A: Allocator,
"," as RenderHtml>::AsyncOutput":"

Notable traits for Vec<u8, A>

impl<A> Write for Vec<u8, A>
where\n A: Allocator,
","Either":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
","Either":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
","Either":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
","Either":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
","Either":"

Notable traits for Either<A, B>

impl<Item, A, B> Iterator for Either<A, B>
where\n A: Iterator<Item = Item>,\n B: Iterator<Item = Item>,
type Item = Item;
"}