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:
counteris the classic counter example, showing the basics of client-side rendering and reactive DOM updates.counter_without_macrosadapts the counter example to use the builder pattern for the UI and avoids other macros, instead showing the code that Leptos generates.countersintroduces parent-child communication via contexts, and the<For/>component for efficient keyed list updates.error_boundaryshows how to useResulttypes to handle errors.parent_childshows four different ways a parent component can communicate with a child, including passing a closure, context, and more.fetchintroducesResources, which allow you to integrate arbitraryasynccode like an HTTP request within your reactive code.routershows how to use Leptos’s nested router to enable client-side navigation and route-specific, reactive data loading.slotsshows how to use slots on components.spreadshows how the spread syntax can be used to spread data and/or event handlers onto elements.counter_isomorphicshows different methods of interaction with a stateful server, including server functions, server actions, forms, and server-sent events (SSE).todomvcshows 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 useEffect::newto serialize JSON tolocalStorageand reactively call DOM methods on references to elements.hackernewsandhackernews_axumintegrate 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_sqliteandtodo_app_sqlite_axumshow how to build a full-stack app using server functions and database connections.tailwindshows how to integrate TailwindCSS withtrunkfor CSR.
Details on how to run each example can be found in its README.
§Quick Links
Here are links to the most important sections of the docs:
- Reactivity: the
reactive_graphoverview, and more details in- signals:
signal,ReadSignal,WriteSignalandRwSignal. - computations:
Memo. asyncinterop:Resourcefor loading data usingasyncfunctions andActionto mutate data or imperatively callasyncfunctions.- reactions:
EffectandRenderEffect.
- signals:
- Templating/Views: the
viewmacro andIntoViewtrait. - Routing: the
leptos_routercrate - Server Functions: the
servermacro andServerAction.
§Feature Flags
nightly: OnnightlyRust, enables the function-call syntax for signal getters and setters. Also enables some experimental optimizations that improve the handling of static strings and the performance of thetemplate! {}macro.csrClient-side rendering: Generate DOM nodes in the browser.ssrServer-side rendering: Generate an HTML string (typically on the server).islandsActivates “islands mode,” in which components are not made interactive on the client unless they use the#[island]macro.hydrateHydration: use this to add interactivity to an SSRed Leptos app.nonceAdds support for nonces to be added as part of a Content Security Policy.rkyvIn SSR/hydrate mode, enables usingrkyvto serialize resources.tracingAdds support fortracing.trace-component-propsAddstracingsupport for component props.delegationUses event delegation rather than the browser’s native event handling system. (This improves the performance of creating large numbers of elements simultaneously, in exchange for occasional edge cases in which events behave differently from native browser events.)rustlsUserustlsfor server functions.
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;pub use wasm_split_helpers;
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
childrenprop 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..nother 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
- 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
viewmacro, but loads the view from an external file instead of parsing it inline. - memo
- Generates a
memointo a struct with a default getter. - slice
- Generates a
sliceinto a struct with a default getter and setter. - template
- The
templatemacro behaves likeview, except that it wraps the entire tree in aViewTemplate. 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
viewmacro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences:
Traits§
- Into
View - 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
islandsfeature of Leptos. Apart from the macro name, the API is the same as thecomponentmacro. - lazy
- The
#[lazy]macro indicates that a function can be lazy-loaded from a separate WebAssembly (WASM) 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
ssrfeature 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.