Home

Awesome

Leptos Struct Table

Crates.io Docs MIT/Apache 2.0 Build Status built with Codeium

<!-- cargo-rdme start -->

Easily create Leptos table components from structs.

Hero Image

Features

Usage

use leptos::*;
use leptos_struct_table::*;

#[derive(TableRow, Clone)]
#[table(impl_vec_data_provider)]
pub struct Person {
    id: u32,
    name: String,
    age: u32,
}

fn main() {
    mount_to_body(|| {
        let rows = vec![
            Person { id: 1, name: "John".to_string(), age: 32 },
            Person { id: 2, name: "Jane".to_string(), age: 28 },
            Person { id: 3, name: "Bob".to_string(), age: 45 },
        ];

        view! {
            <table>
                <TableContent rows />
            </table>
        }
    });
}

Server-Side Rendering

To use this with Leptos' server-side rendering, you can have to add leptos-use as a dependency to your Cargo.toml and then configure it for SSR like the following.

[dependencies]
leptos-use = "<current version>"
# ...

[features]
hydrate = [
    "leptos/hydrate",
    # ...
]
ssr = [
    "leptos/ssr",
    # ...
    "leptos-use/ssr",
]

Please see the serverfn_sqlx example for a working project with SSR.

Data Providers

As shown in the inital usage example, when you add #[table(impl_vec_data_provider)] to your struct, the table will automatically generate a data provider for you. You can then directly pass a Vec<T> to the rows prop. Internally this implements the trait [TableDataProvider] for Vec<T>.

To leverage the full power of async partial data loading with caching you should implement the trait [PaginatedTableDataProvider] or the trait [TableDataProvider] yourself. It's quite easy to do so. Which of the two traits you choose depends on your data source. If your data source provides paginated data, as is the case for many REST APIs, you should implement [PaginatedTableDataProvider]. Otherwise you should probably implement [TableDataProvider].

See the paginated_rest_datasource example and the serverfn_sqlx example for working demo projects that implement these traits.

Macro options

The #[table(...)] attribute can be used to customize the generated component. The following options are available:

Struct attributes

These attributes can be applied to the struct itself.

Field attributes

These attributes can be applied to any field in the struct.

Formatting

The format attribute can be used to customize the formatting of cells. It is an easier alternative to creating a custom renderer when you just want to customize some basic formatting. It is type safe and tied to the type the formatting is applied on. see [CellValue] and the associated type for the type you are rendering to see a list of options

See:

Features

Classes Customization

Classes can be easily customized by using the classes_provider attribute on the struct. You can specify any type that implementats the trait [TableClassesProvider]. Please see the documentation for that trait for more information. You can also look at [TailwindClassesPreset] for an example how this can be implemented.

Example:

#[derive(TableRow, Clone)]
#[table(classes_provider = "TailwindClassesPreset")]
pub struct Book {
    id: u32,
    title: String,
}

Field Getters

Sometimes you want to display a field that is not part of the struct but a derived value either from other fields or sth entirely different. For this you can use either the [FieldGetter] type or the getter attribute.

Let's start with [FieldGetter] and see an example:

#[derive(TableRow, Clone)]
#[table(classes_provider = "TailwindClassesPreset")]
pub struct Book {
    id: u32,
    title: String,
    author: String,

    // this tells the macro that you're going to provide a method called `title_and_author` that returns a `String`
    title_and_author: FieldGetter<String>
}

impl Book {
    // Returns the value that is displayed in the column
    pub fn title_and_author(&self) -> String {
        format!("{} by {}", self.title, self.author)
    }
}

To provide maximum flexibility you can use the getter attribute.

#[derive(TableRow, Clone)]
#[table(classes_provider = "TailwindClassesPreset")]
pub struct Book {
    // this tells the macro that you're going to provide a method called `get_title` that returns a `String`
    #[table(getter = "get_title")]
    title: String,
}

impl Book {
    pub fn get_title(&self) -> String {
        format!("Title: {}", self.title)
    }
}

When to use FieldGetter vs getter attribute

A field of type FieldGetter<T> is a virtual field that doesn't really exist on the struct. Internally FieldGetter is just a new-typed PhatomData and thus is removed during compilation. Hence it doesn't increase memory usage. That means you should use it for purely derived data.

The getter attribute should be used on a field that actually exists on the struct but whose value you want to modify before it's rendered.

Custom Renderers

Custom renderers can be used to customize almost every aspect of the table. They are specified by using the various ...renderer attributes on the struct or fields or props of the [TableContent] component. To implement a custom renderer please have a look at the default renderers listed below.

On the struct level you can use this attribute:

As props of the [TableContent] component you can use the following:

On the field level you can use the renderer attribute.

It defaults to [DefaultTableCellRenderer] Works for any type that implements the [CellValue] trait that is implemented for types in the standard library, popular crates with feature flags and for your own type if you implement this trait for them.

Example:

#[derive(TableRow, Clone)]
pub struct Book {
    title: String,
    #[table(renderer = "ImageTableCellRenderer")]
    img: String,
}

// Easy cell renderer that just displays an image from an URL.
#[component]
fn ImageTableCellRenderer<F>(
    class: String,
    #[prop(into)] value: MaybeSignal<String>,
    on_change: F,
    index: usize,
) -> impl IntoView
where
    F: Fn(String) + 'static,
{
    view! {
        <td class=class>
            <img src=value alt="Book image" height="64"/>
        </td>
    }
}

For more detailed information please have a look at the custom_renderers_svg example for a complete customization.

Editable Cells

You might have noticed the type parameter F in the custom cell renderer above. This can be used to emit an event when the cell is changed. In the simplest case you can use a cell renderer that uses an <input>.

#[derive(TableRow, Clone, Default, Debug)]
#[table(impl_vec_data_provider)]
pub struct Book {
    id: u32,
    #[table(renderer = "InputCellRenderer")]
    title: String,
}

// Easy input cell renderer that emits `on_change` when the input is changed.
#[component]
fn InputCellRenderer<F>(
    class: String,
    #[prop(into)] value: MaybeSignal<String>,
    on_change: F,
    index: usize,
) -> impl IntoView
where
    F: Fn(String) + 'static,
{
    view! {
        <td class=class>
            <input type="text" value=value on:change=move |evt| { on_change(event_target_value(&evt)); } />
        </td>
    }
}

// Then in the table component you can listen to the `on_change` event:

#[component]
pub fn App() -> impl IntoView {
    let rows = vec![Book::default(), Book::default()];

    let on_change = move |evt: ChangeEvent<Book>| {
        logging::log!("Changed row at index {}:\n{:#?}", evt.row_index, evt.changed_row);
    };

    view! {
        <table>
            <TableContent rows on_change />
        </table>
    }
}

Please have a look at the editable example for fully working example.

Pagination / Virtualization / InfiniteScroll

This table component supports different display acceleration strategies. You can set them through the display_strategy prop of the [TableContent] component.

The following options are available. Check their docs for more details.

Please have a look at the pagination example for more information on how to use pagination.

I18n

To translate the column titles of the table using leptos-i18n you can enable the "i18n" feature. The field names of the struct are used as keys.

Please have a look at the i18n example.

Contribution

All contributions are welcome. Please open an issue or a pull request if you have any ideas or problems.

<!-- cargo-rdme end -->

Leptos Compatibility

Crate versionCompatible Leptos version
<= 0.20.3
0.30.4
0.4, 0.5, 0.60.5
0.7 – 0.120.6