Use Random

A Rust/UI hook that generates unique random IDs for DOM elements and CSS animations.

utilsanimationcss

Installation

You can run either of the following commands:

# cargo install ui-cli --force
ui add demo_use_random
ui add use_random

Update the imports to match your project setup.

Copy and paste the following code into your project:

components/ui/use_random.rs

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicUsize, Ordering};

const PREFIX: &str = "rust_ui"; // Must NOT contain "/" or "-"

pub fn use_random_id() -> String {
    format!("_{PREFIX}_{}", generate_hash())
}

pub fn use_random_id_for(element: &str) -> String {
    format!("{}_{PREFIX}_{}", element, generate_hash())
}

pub fn use_random_transition_name() -> String {
    let random_id = use_random_id();
    format!("view-transition-name: {random_id}")
}

/* ========================================================== */
/*                     ✨ FUNCTIONS ✨                        */
/* ========================================================== */

static COUNTER: AtomicUsize = AtomicUsize::new(1);

fn generate_hash() -> u64 {
    let mut hasher = DefaultHasher::new();
    let counter = COUNTER.fetch_add(1, Ordering::SeqCst);
    counter.hash(&mut hasher);
    hasher.finish()
}

Update the imports to match your project setup.

Usage

// Coming soon

Examples

Random ID Generation

  • Rust/UI Icons - CopyCopy Demo

Random ID Hook

Generated ID: _rust_ui_7998789120319600614

use leptos::prelude::*;

use crate::components::hooks::use_random::use_random_id;

#[component]
pub fn DemoUseRandom() -> impl IntoView {
    let checkbox_id = use_random_id();

    view! {
        <div class="p-4 mx-auto space-y-4 max-w-md">
            <h3 class="font-semibold">"Random ID Hook"</h3>

            <p class="text-sm">
                "Generated ID: " <code class="py-1 px-2 text-xs rounded bg-muted">{checkbox_id.clone()}</code>
            </p>

            <div class="flex items-center space-x-2">
                <input type="checkbox" id=checkbox_id />
                <label class="text-sm">"Checkbox with unique ID"</label>
            </div>
        </div>
    }
}