Of course! Creating a reusable modal component is a great way to learn about state management, component props, and event handling in Dioxus.
Here is a complete, self-contained example of a Dioxus application that features a reusable Modal component.
1. Project Setup
First, make sure you have a Dioxus project. If not, create one:
bash
# Install the dioxus CLI if you don't have it
cargo install dioxus-cli
# Create a new desktop project
dioxus new my_modal_app --template desktop
cd my_modal_app
Now, you'll need to add dioxus to your Cargo.toml. Your [dependencies] section should look like this:
Cargo.toml
toml
[package]
name = "my_modal_app"
version = "0.1.0"
edition = "2021"
[dependencies]
dioxus = "0.5"
# Or if you created a desktop app:
# dioxus-desktop = "0.5"
(The template might already have this set up for you)
2. The Code (src/main.rs)
Replace the contents of your src/main.rs with the following code. It contains the main App component and the reusable Modal component.
rust
#![allow(non_snake_case)] // Dioxus components use PascalCase
use dioxus::prelude::*;
fn main() {
// Launch the app
launch(App);
}
// The main App component
#[component]
fn App() -> Element {
// A signal to control the modal's visibility.
// `false` means it's hidden by default.
let mut is_modal_open = use_signal(|| false);
rsx! {
// We include the CSS styles directly for this example
style { {include_str!("./styles.css")} }
div {
class: "app-container",
h1 { "Dioxus Modal Example" }
p { "Click the button below to open the modal." }
// This button will set the signal to `true`, showing the modal
button {
onclick: move |_| is_modal_open.set(true),
"Open Modal"
}
// --- The Modal Component ---
// It's always "rendered" here, but its internal logic
// will only show it if `is_modal_open` is true.
Modal {
// Pass the signal to the component
is_open: is_modal_open,
// Define the event handler for closing the modal
on_close: move |_| is_modal_open.set(false),
// This is the content that will be displayed *inside* the modal
// It's passed as the `children` prop.
h2 { "This is a Modal!" }
p { "You can put any content you want in here." }
p { "For example, a form, some information, or another button." }
button {
class: "button-secondary",
// This button inside the modal can also close it
onclick: move |_| is_modal_open.set(false),
"Close from inside"
}
}
}
}
}
// --- The Reusable Modal Component ---
/// The properties the Modal component accepts.
#[derive(Props, PartialEq, Clone)]
struct ModalProps {
// A signal to show/hide the modal. The component can read and write to it.
is_open: Signal<bool>,
// An event handler that is called when the modal requests to be closed.
on_close: EventHandler<()>,
// The content to display inside the modal.
children: Element,
}
#[component]
fn Modal(props: ModalProps) -> Element {
// If the `is_open` signal is false, we render nothing.
if !props.is_open() {
return None;
}
// When the signal is true, we render the modal structure.
rsx! {
// 1. The semi-transparent backdrop
div {
class: "modal-backdrop",
// Clicking the backdrop calls the on_close event handler
onclick: move |_| props.on_close.call(()),
// 2. The modal content window
div {
class: "modal-content",
// IMPORTANT: Stop click propagation
// This prevents a click inside the modal from bubbling up
// to the backdrop and closing the modal.
onclick: move |event| event.stop_propagation(),
// 3. The close button (top right)
button {
class: "modal-close-btn",
onclick: move |_| props.on_close.call(()),
"×" // A common "close" icon
},
// 4. The content passed from the parent
{props.children}
}
}
}
}
3. The Styling (src/styles.css)
For the modal to look correct, you need some CSS. Create a new file named styles.css in the src/ directory, next to your main.rs.
src/styles.css
css
/* General App Styling */
.app-container {
font-family: sans-serif;
text-align: center;
padding: 2rem;
}
/* --- Modal Styling --- */
/* The full-screen, semi-transparent background */
.modal-backdrop {
position: fixed; /* Sits on top of the content */
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
display: flex; /* Use flexbox to center the content */
justify-content: center;
align-items: center;
z-index: 1000; /* Ensures it's on top of other content */
}
/* The white box that contains the modal's content */
.modal-content {
background-color: white;
padding: 2rem;
padding-top: 3rem; /* Extra padding at top for the close button */
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
min-width: 300px;
max-width: 90%;
position: relative; /* Needed to position the close button */
}
/* The 'X' button in the top-right corner */
.modal-close-btn {
position: absolute;
top: 10px;
right: 15px;
background: none;
border: none;
font-size: 1.5rem;
font-weight: bold;
color: #888;
cursor: pointer;
}
.modal-close-btn:hover {
color: #000;
}
/* Styling for buttons in the example */
button {
padding: 10px 20px;
font-size: 1rem;
border-radius: 5px;
cursor: pointer;
border: 1px solid #007bff;
background-color: #007bff;
color: white;
margin: 5px;
}
button:hover {
background-color: #0056b3;
}
button.button-secondary {
background-color: #6c757d;
border-color: #6c757d;
}
button.button-secondary:hover {
background-color: #5a6268;
}
4. Run the Application
Now, you can run your app from the terminal:
bash
cargo run
You should see a window with a button. Clicking the button will open the modal, and you can close it by clicking the '×' button, the backdrop, or the "Close from inside" button.
How It Works: Key Concepts
State Management (use_signal): The is_modal_open signal in the App component holds the state of the modal (open or closed). use_signal is Dioxus's primary tool for reactive state. When the signal's value changes, any part of the UI that reads from it will automatically re-render.
Component Props (#[derive(Props)]): The Modal component is made reusable by defining ModalProps. This allows the parent component (App) to pass down the necessary data and behavior:
is_open: The control signal.
on_close: An EventHandler that lets the Modal tell its parent "I need to be closed," without knowing how to close itself. This is great for decoupling components.
children: This special prop allows you to pass JSX/RSX content from the parent to the child, making the Modal a generic container.
Conditional Rendering: The Modal component cleverly renders None (nothing) when is_open() is false. This is the most efficient way to hide a component in Dioxus.
Event Handling (onclick): Standard onclick handlers are used to change the state. The "Open Modal" button sets is_modal_open to true. The close buttons and the backdrop trigger the on_close event handler, which in turn sets the signal to false.
Event Propagation (event.stop_propagation()): This is a crucial detail. When you click on the modal-content, that click event would normally "bubble up" to its parent, the modal-backdrop. Since the backdrop has an onclick handler to close the modal, clicking anywhere inside the content would also close it. event.stop_propagation() prevents this, ensuring only clicks on the backdrop itself (or the explicit close buttons) will close the modal.