Here's an example of a simple modal component using Rust and Dioxus:
use dioxus::prelude::*;
fn Modal(cx: Scope, props: Props) -> Element {
let is_open = use_state(cx, || false);
cx.render(rsx! {
button {
onclick: move |_| is_open.set(true),
"Open Modal"
}
if *is_open.get() {
rsx! {
div {
class: "modal-overlay",
onclick: move |_| is_open.set(false),
div {
class: "modal-content",
h2 { "Modal Title" }
p { "This is a modal" }
button {
onclick: move |_| is_open.set(false),
"Close"
}
}
}
}
} else {
rsx! {}
}
})
}
fn main() {
dioxus::desktop::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx! {
Modal {}
})
}
In this example, we create a Modal component that displays a button. When the button is clicked, it sets the is_open state to true, which renders the modal. The modal has a close button that sets is_open to false when clicked, hiding the modal.
The modal is rendered conditionally based on the is_open state. If is_open is true, the modal is rendered; otherwise, an empty rsx! is rendered.
You can customize the modal's appearance by adding CSS classes to the div elements and styling them in your CSS file.
To make the modal more reusable, you can add props to the Modal component to customize its title, content, and other properties. For example:
fn Modal(cx: Scope, props: Props) -> Element {
let is_open = use_state(cx, || false);
let title = props.title.clone();
let content = props.content.clone();
cx.render(rsx! {
button {
onclick: move |_| is_open.set(true),
"Open Modal"
}
if *is_open.get() {
rsx! {
div {
class: "modal-overlay",
onclick: move |_| is_open.set(false),
div {
class: "modal-content",
h2 { title }
p { content }
button {
onclick: move |_| is_open.set(false),
"Close"
}
}
}
}
} else {
rsx! {}
}
})
}
#[derive(Props)]
struct Props {
title: String,
content: String,
}
fn main() {
dioxus::desktop::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx! {
Modal {
title: "My Modal".to_string(),
content: "This is my modal content".to_string(),
}
})
}
In this example, we add title and content props to the Modal component, which are used to render the modal's title and content. We also derive the Props trait for the Props struct, which allows us to use it as a prop type in the Modal component.