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 from the todomvc example. 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 create_effect 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
  • serde (Default) In SSR/hydrate mode, uses serde to serialize resources and send them from the server to the client.
  • serde-lite In SSR/hydrate mode, uses serde-lite to serialize resources and send them from the server to the client.
  • rkyv In SSR/hydrate mode, uses rkyv to serialize resources and send them from the server to the client.
  • miniserde In SSR/hydrate mode, uses miniserde to serialize resources and send them from the server to the client.
  • tracing Adds additional support for tracing to components.
  • default-tls Use default native TLS support. (Only applies when using server functions with a non-WASM client like a desktop app.)
  • rustls Use rustls. (Only applies when using server functions with a non-WASM client like a desktop app.)
  • template_macro Enables the template! macro, which offers faster DOM node creation for some use cases in csr.

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::*;

#[component]
pub fn SimpleCounter( initial_value: i32) -> impl IntoView {
    // create a reactive signal with the initial value
    let (value, set_value) = create_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.update(|value| *value -= 1);
    let increment = move |_| set_value.update(|value| *value += 1);

    view! {

        <div>
            <button on:click=clear>"Clear"</button>
            <button on:click=decrement>"-1"</button>
            <span>"Value: " {move || value.get().to_string()} "!"</span>
            <button on:click=increment>"+1"</button>
        </div>
    }
}

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


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

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

Re-exports§

Modules§

  • 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 to make it easier to handle errors in your application.
  • Types for all DOM events.
  • Exports types for working with HTML elements.
  • Utilities for simple isomorphic logging to the console or terminal.
  • Exports types for working with MathML elements.
  • Utilities for exporting nonces to be used for a Content Security Policy.
  • 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.
  • This prelude imports all signal types as well as all signal traits needed to use those types.
  • Utilities for server-side rendering HTML.
  • Types that handle asynchronous data loading via <Suspense/>.
  • Exports types for working with SVG elements.

Macros§

Structs§

  • An action synchronizes an imperative async call to the synchronous reactive system.
  • A collection of additional HTML attributes to be applied to an element, each of which may or may not be reactive.
  • Iterator over additional HTML attributes.
  • Props for the AnimatedShow component.
  • Props for the Await component.
  • Callbacks define a standard way to store functions and closures.
  • Handle to dispose of a reactive node.
  • A handle to an effect, can be used to explicitly dispose of the effect.
  • Props for the ErrorBoundary component.
  • A struct to hold all the possible errors that could be provided by child Views
  • Props for the For component.
  • Represents a group of views.
  • Represents its pending <Suspense/> fragment.
  • A single, global suspense context that will be checked when resources are read. This won’t be “blocked” by lower suspense components. This is useful for e.g., holding route transitions.
  • Represents an HTML element.
  • This struct serves as a convenient place to store details used for configuring Leptos. It’s used in our actix and axum integrations to generate the correct path for WASM, JS, and Websockets, as well as other configuration tasks. It shares keys with cargo-leptos, to allow for easy interoperability
  • A wrapping type for an optional component prop, which can either be a signal or a non-reactive value, and which may or may not have a value. In other words, this is an Option<MaybeSignal<Option<T>>> that automatically flattens its getters.
  • An efficient derived reactive value based on other reactive values.
  • An action that synchronizes multiple imperative async calls to the reactive system, tracking the progress of each one.
  • Contains a shared reference to a DOM node created while using the view macro to create your UI.
  • A reactive owner.
  • Props for the Portal component.
  • Props for the Provider component.
  • The getter for a reactive signal.
  • A signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Unique ID assigned to a Resource.
  • Unique ID assigned to a Runtime.
  • A signal that combines the getter and setter into one value, rather than separating them into a ReadSignal and a WriteSignal. You may prefer this its style, or it may be easier to pass around in a context or as a function argument.
  • Allows running a future that has access to a given scope.
  • A conditional signal that only notifies subscribers when a change in the source signal’s value changes whether the given function is true.
  • Props for the Show component.
  • A wrapper for any kind of readable reactive signal: a ReadSignal, Memo, RwSignal, or derived signal closure.
  • A wrapper for any kind of settable reactive signal: a WriteSignal, RwSignal, or closure that receives a value and sets a signal depending on it.
  • A non-reactive wrapper for any value, which can be created with store_value.
  • Tracks Resources that are read under a suspense context, i.e., within a Suspense component.
  • Props for the Suspense component.
  • A callback type that is Send and Sync if its input type is Send and Sync. Otherwise, you can use exactly the way you use Callback.
  • Describes a value that is either a static or a reactive string, i.e., a String, a &str, or a reactive Fn() -> String.
  • Props for the Transition component.
  • Reactive Trigger, notifies reactive code to rerun.
  • New-type wrapper for the a function that returns a view with From and Default traits implemented to enable optional props in for example <Show> and <Suspense>.
  • The setter for a reactive signal.

Enums§

  • Represents the different possible values an attribute node could have.
  • Bind data through attributes, or behavior through event handlers, to an element. A value of any type able to provide an iterator of bindings (like a: Vec<Binding>), can be spread onto an element using the spread syntax view! { <div {..bindings} /> }.
  • Represents the different possible values a single class on an element could have, allowing you to do fine-grained updates to single items in Element.classList.
  • A statically typed event handler.
  • Error returned from Oco::try_from for unsuccessful conversion from Oco<'_, [u8]> to Oco<'_, str>.
  • A wrapper for a value that is either T or Signal<T>.
  • “Owned Clones Once”: a smart pointer that can be either a reference, an owned value, or a reference-counted pointer. This is useful for storing immutable values, such as strings, in a way that is cheap to clone and pass around.
  • Represents the different possible values an element property could have, allowing you to do fine-grained updates to single fields.
  • Describes errors that can occur while serializing and deserializing data, typically during the process of streaming Resources from the server to the client.
  • Type for errors that can occur when using server functions.
  • Type for errors that can occur when using server functions.
  • A leptos view which can be mounted to the DOM.

Traits§

  • A wrapper trait for calling callbacks.
  • Collects an iterator or collection into a View.
  • Converts some type into an Attribute.
  • Converts some type into a Class.
  • Converts some type into a Property.
  • Helper trait for converting Fn() -> T closures into Signal<T>.
  • Helper trait for converting Fn(T) into SignalSetter<T>.
  • Converts some type into a Style.
  • Converts the value into a View.
  • Describes an object that can be serialized to or from a supported format Currently those are JSON and Cbor
  • This trait allows disposing a signal before its owner has been disposed.
  • This trait allows getting an owned value of the signals inner type.
  • Trait implemented for all signal types which you can get a value from, such as ReadSignal, Memo, etc., which allows getting the inner value without subscribing to the current scope.
  • This trait allows setting the value of a signal.
  • Trait implemented for all signal types which you can set the inner value, such as WriteSignal and RwSignal, which allows setting the inner value without causing effects which depend on the signal from being run.
  • This trait allows converting a signal into a async Stream.
  • This trait allows updating the inner value of a signal.
  • This trait allows updating the signals value without causing dependant effects to run.
  • This trait allows obtaining an immutable reference to the signal’s inner type.
  • This trait allows getting a reference to the signals inner value without creating a dependency on the signal.
  • This trait can be used when constructing a component that takes children without needing to know exactly what children type the component expects. This is used internally by the view! macro implementation, and can also be used explicitly when using the builder syntax.

Functions§

  • A component that will show its children when the when condition is true. Additionally, you need to specify a hide_delay. If the when condition changes to false, the unmounting of the children will be delayed by the specified Duration. If you provide the optional show_class and hide_class, you can create very easy mount / unmount animations.
  • Allows you to inline the data loading for an async block or server function directly into your view. This is the equivalent of combining a create_resource that only loads once (i.e., with a source signal || ()) with a Suspense with no fallback.
  • When you render a Result<_, _> in your view, in the Err case it will render nothing, and search up through the view tree for an <ErrorBoundary/>. This component lets you define a fallback that should be rendered in that error case, allowing you to handle errors within a section of the interface.
  • Iterates over children and displays them, keyed by the key function given.
  • Renders components somewhere else in the DOM.
  • Uses the context API to provide_context to its children and descendants, without overwriting any contexts of the same type in its own reactive scope.
  • A component that will show its children when the when condition is true, and show the fallback when it is false, without rerendering every time the condition changes.
  • If any Resource is read in the children of this component, it will show the fallback while they are loading. Once all are resolved, it will render the children.
  • If any Resources are read in the children of this component, it will show the fallback while they are loading. Once all are resolved, it will render the children. Unlike Suspense, this will not fall back to the fallback state if there are further changes after the initial load.
  • Wraps the given function so that, whenever it is called, it creates a child node owned by whichever reactive node was the owner when it was created, runs the function, and returns a disposer that can be used to dispose of the child later.
  • Batches any reactive updates, preventing effects from running until the whole function has run. This allows you to prevent rerunning effects if multiple signal updates might cause the same effect to run.
  • Creates an Action to synchronize an imperative async call to the synchronous reactive system.
  • Creates a “blocking” Resource. When server-side rendering is used, this resource will cause any <Suspense/> you read it under to block the initial chunk of HTML from being sent to the client. This means that if you set things like HTTP headers or <head> metadata in that <Suspense/>, that header material will be included in the server’s original response.
  • Effects run a certain chunk of code whenever the signals they depend on change. create_effect queues the given function to run once, tracks its dependence on any signal values read within it, and reruns the function whenever the value of a dependency changes.
  • Creates an effect; unlike effects created by create_effect, isomorphic effects will run on the server as well as the client.
  • Creates a local Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Creates a local Resource with the given initial value, which will only generate and run a Future using the fetcher when the source changes.
  • Creates an efficient derived reactive value based on other reactive values.
  • Creates a MultiAction to synchronize an imperative async call to the synchronous reactive system.
  • Creates a shared reference to a DOM node created while using the view macro to create your UI.
  • Like create_memo, create_owning_memo creates an efficient derived reactive value based on other reactive values, but with two differences:
  • Takes a memoized, read-only slice of a signal. This is equivalent to the read-only half of create_slice.
  • Creates an effect exactly like create_effect, but runs immediately rather than being queued until the end of the current microtask. This is mostly used inside the renderer but is available for use cases in which scheduling the effect for the next tick is not optimal.
  • Creates a Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Creates a Resource with the given initial value, which will only generate and run a Future using the fetcher when the source changes.
  • Creates a new reactive runtime and sets it as the current runtime.
  • Creates a reactive signal with the getter and setter unified in one value. You may prefer this style, or it may be easier to pass around in a context or as a function argument.
  • Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether it is equal to the key value (as determined by PartialEq.)
  • Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether the given function is true.
  • Creates an Action that can be used to call a server function.
  • Creates a MultiAction that can be used to call a server function.
  • Creates a signal, the basic reactive primitive.
  • Creates a signal that always contains the most recent value emitted by a Stream. If the stream has not yet emitted a value since the signal was created, the signal’s value will be None.
  • Derives a reactive slice of an RwSignal.
  • Creates a Trigger, a kind of reactive primitive.
  • Creates a setter to access one slice of a signal. This is equivalent to the write-only half of create_slice.
  • The current reactive runtime.
  • Returns the Document.
  • Helper function to extract Event.target from any event.
  • Helper function to extract event.target.checked from an event.
  • Helper function to extract event.target.value from an event.
  • Extracts a context value of type T from the reactive system by traversing it upwards, beginning from the current reactive owner and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context.
  • Loads LeptosOptions from a Cargo.toml with layered overrides. If an env var is specified, like LEPTOS_ENV, it will override a setting in the file. It takes in an optional path to a Cargo.toml file. If None is provided, you’ll need to set the options as environment variables or rely on the defaults. This is the preferred approach for cargo-leptos. If Some(“./Cargo.toml”) is provided, Leptos will read in the settings itself. This option currently does not allow dashes in file or folder names, as all dashes become underscores
  • Runs the provided closure and mounts the result to the provided element.
  • Runs the provided closure and mounts the result to the <body>.
  • Creates a cleanup function, which will be run when the current reactive owner is disposed.
  • Provides a context value of type T to the current reactive node and all of its descendants. This can be consumed using use_context.
  • The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser’s event loop.
  • Runs the given function between the next repaint using Window.requestAnimationFrame.
  • Runs the given function between the next repaint using Window.requestAnimationFrame, returning a cancelable handle.
  • Queues the given function during an idle period using Window.requestIdleCallback.
  • Queues the given function during an idle period using Window.requestIdleCallback, returning a cancelable handle.
  • Runs the given function as a child of the current Owner, once.
  • Sets the current reactive runtime.
  • Repeatedly calls the given function, with a delay of the given duration between calls, returning a cancelable handle. See setInterval().
  • Repeatedly calls the given function, with a delay of the given duration between calls, returning a cancelable handle. See setInterval().
  • Executes the given function after the given duration of time has passed. setTimeout().
  • Executes the given function after the given duration of time has passed, returning a cancelable handle. setTimeout().
  • Spawns and runs a thread-local Future in a platform-independent way.
  • Runs a future that has access to the provided Owner’s scope context.
  • Runs a future that has access to the provided Owner’s scope context.
  • Creates a non-reactive wrapper for any value by storing it within the reactive system.
  • Attempts to batch any reactive updates, preventing effects from running until the whole function has run. This allows you to prevent rerunning effects if multiple signal updates might cause the same effect to run.
  • Runs a future that has access to the provided Owner’s scope context.
  • Runs a future that has access to the provided Owner’s scope context.
  • Runs the given code with the given reactive owner.
  • Suspends reactive tracking while running the given function.
  • Extracts a context value of type T from the reactive system by traversing it upwards, beginning from the current reactive owner and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context.
  • A version of create_effect that listens to any dependency that is accessed inside deps and returns a stop handler.
  • Returns the Window.
  • Creates a window event listener from a typed event, returning a cancelable handle.
  • Adds an event listener to the Window, typed as a generic Event, returning a cancelable handle.
  • Wraps the given function so that, whenever it is called, it is run in the reactive scope of whatever the reactive owner was when it was created.
  • Runs the given code with the given reactive owner.

Type Aliases§

  • A type for taking anything that implements IntoAttribute.
  • The most common type for the children property on components, which can only be called once.
  • A type for the children property on components that can be called more than once.
  • A type for the children property on components that can be called more than once, but may mutate the children.

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.