docs: move reference up a level

This commit is contained in:
Jonathan Kelley committed 2021-09-24 12:11:05 -04:00
1 parent f8e569a8be
commit 1464d2e0a7
24 files changed
+1 -1

No files matched your search

+1 -1
View File
@@ -20,8 +20,8 @@ pub struct Client {
}
static App: FC<()> = |cx, _| {
let scene = use_state(cx, || Scene::ClientsList);
let clients = use_ref(cx, || vec![] as Vec<Client>);
let scene = use_state(cx, || Scene::ClientsList);
let firstname = use_state(cx, || String::new());
let lastname = use_state(cx, || String::new());
-29
View File
@@ -1,29 +0,0 @@
# Reference Guide
This folder holds a bunch of useful reference code. However, none of the code is meant to be executed (nothing special will happen).
| Reference: | What it does |
| --------------------------------------------------- | ----------------------------------- |
| [Basics](./basics.rs) | How to handle futures with suspense |
| [Empty](./empty.rs) | How to handle futures with suspense |
| [Children](./children.rs) | How to handle futures with suspense |
| [Async](./async.rs) | How to handle futures with suspense |
| [Suspense](./suspense.rs) | How to handle futures with suspense |
| [Conditional Rendering](./conditional_rendering.rs) | How to handle futures with suspense |
| [Controlled Inputs](./controlled_inputs.rs) | How to handle futures with suspense |
| [Fragments](./fragments.rs) | How to handle futures with suspense |
| [Inline Styles](./inline_styles.rs) | How to handle futures with suspense |
| [Spread Pattern for Props](./spreadpattern.rs) | How to handle futures with suspense |
| [Iterators](./iterators.rs) | How to handle futures with suspense |
| [Listener](./listener.rs) | How to handle futures with suspense |
| [Memo](./memo.rs) | How to handle futures with suspense |
| [NodeRef](./noderefs.rs) | How to handle futures with suspense |
| [Signals](./signals.rs) | How to handle futures with suspense |
| [ToString](./tostring.rs) | How to handle futures with suspense |
| [Global CSS](./global_css.rs) | How to handle futures with suspense |
| [State Management](./statemanagement.rs) | How to handle futures with suspense |
| [Testing](./testing.rs) | How to handle futures with suspense |
| [Custom Elements](./custom_elements.rs) | How to handle futures with suspense |
| [Web Components](./webcomponents.rs) | How to handle futures with suspense |
| [Anti-patterns](./antipatterns.rs) | What not to do! |
-181
View File
@@ -1,181 +0,0 @@
//! Example: Antipatterns
//! ---------------------
//!
//! This example shows what *not* to do and provides a reason why a given pattern is considered an "AntiPattern". Most
//! anti-patterns are considered wrong to due performance reasons or violate the "rules" of Dioxus. These rules are
//! borrowed from other successful UI frameworks, and Dioxus is more focused on providing a familiar, ergonomic interface
//! rather than building new harder-to-misuse patterns.
//!
//! In this list we showcase:
//! - Not adding keys for iterators
//! - Heavily nested fragments
//! - Understadning ordering of set_state
//! - Naming conventions
//! - Rules of hooks
//!
//! Feel free to file a PR or Issue if you run into another antipattern that you think users of Dioxus should know about.
use dioxus::prelude::*;
/// Antipattern: Iterators without keys
/// -----------------------------------
///
/// This is considered an anti-pattern for performance reasons. Dioxus will diff your current and old layout and must
/// take a slower path if it can't correlate old elements with new elements. Lists are particularly susceptible to the
/// "slow" path, so you're strongly encouraged to provide a unique ID stable between renders. Additionally, providing
/// the *wrong* keys is even worse - props might be assigned to the wrong components! Keys should be:
/// - Unique
/// - Stable
/// - Predictable
///
/// Dioxus will log an error in the console if it detects that your iterator does not properly generate keys
#[derive(PartialEq, Props)]
struct NoKeysProps {
data: std::collections::HashMap<u32, String>,
}
static AntipatternNoKeys: FC<NoKeysProps> = |cx, props| {
// WRONG: Make sure to add keys!
rsx!(cx, ul {
{props.data.iter().map(|(k, v)| rsx!(li { "List item: {v}" }))}
});
// RIGHT: Like this:
rsx!(cx, ul {
{props.data.iter().map(|(k, v)| rsx!(li { key: "{k}", "List item: {v}" }))}
})
};
/// Antipattern: Deeply nested fragments
/// ------------------------------------
///
/// This particular antipattern is not necessarily an antipattern in other frameworks but does has a performance impact
/// in Dioxus apps. Fragments don't mount a physical element to the dom immediately, so Dioxus must recurse into its
/// children to find a physical dom node. This process is called "normalization". Other frameworks perform an agressive
/// mutative normalization while Dioxus keeps your VNodes immutable. This means that deepely nested fragments make Dioxus
/// perform unnecessary work. Prefer one or two levels of fragments / nested components until presenting a true dom element.
///
/// Only Component and Fragment nodes are susceptible to this issue. Dioxus mitigates this with components by providing
/// an API for registering shared state without the ContextProvider pattern.
static AntipatternNestedFragments: FC<()> = |cx, props| {
// Try to avoid heavily nesting fragments
rsx!(cx,
Fragment {
Fragment {
Fragment {
Fragment {
Fragment {
div { "Finally have a real node!" }
}
}
}
}
}
)
};
/// Antipattern: Using state after its been updated
/// -----------------------------------------------
///
/// This is an antipattern in other frameworks, but less so in Dioxus. However, it's important to highlight that use_state
/// does *not* work the same way as it does in React. Rust provides explicit guards against mutating shared data - a huge
/// problem in JavaScript land. With Rust and Dioxus, it's nearly impossible to misuse `use_state` - you simply can't
/// accidentally modify the state you've received!
///
/// However, calling set_state will *not* update the current version of state in the component. This should be easy to
/// recognize from the function signature, but Dioxus will not update the "live" version of state. Calling `set_state`
/// merely places a new value in the queue and schedules the component for a future update.
static AntipaternRelyingOnSetState: FC<()> = |cx, props| {
let (state, set_state) = use_state(cx, || "Hello world").classic();
set_state("New state");
// This will return false! `state` will *still* be "Hello world"
assert!(state == &"New state");
todo!()
};
/// Antipattern: Capitalization
/// ---------------------------
///
/// This antipattern is enforced to retain parity with other frameworks and provide useful IDE feedback, but is less
/// critical than other potential misues. In short:
/// - Only raw elements may start with a lowercase character
/// - All components must start with an uppercase character
///
/// IE: the following component will be rejected when attempted to be used in the rsx! macro
static antipattern_component: FC<()> = |cx, props| todo!();
/// Antipattern: Misusing hooks
/// ---------------------------
///
/// This pattern is an unfortunate one where Dioxus supports the same behavior as in other frameworks. Dioxus supports
/// "hooks" - IE "memory cells" that allow a value to be stored between renders. This allows other hooks to tap into
/// a components "memory" without explicitly adding all of its data to a struct definition. In Dioxus, hooks are allocated
/// with a bump arena and then immediately sealed.
///
/// This means that hooks may not be misued:
/// - Called out of order
/// - Called in a conditional
/// - Called in loops or callbacks
///
/// For the most part, Rust helps with rule #3 but does not save you from misusing rule #1 or #2. Dioxus will panic
/// if hooks do not downcast the same data between renders. This is validated by TypeId - and eventually - a custom key.
#[derive(PartialEq, Props)]
struct MisuedHooksProps {
should_render_state: bool,
}
static AntipatternMisusedHooks: FC<MisuedHooksProps> = |cx, props| {
if props.should_render_state {
// do not place a hook in the conditional!
// prefer to move it out of the conditional
let (state, set_state) = use_state(cx, || "hello world").classic();
rsx!(cx, div { "{state}" })
} else {
rsx!(cx, div { "Not rendering state" })
}
};
/// Antipattern: Downcasting refs and panicing
/// ------------------------------------------
///
/// Occassionally it's useful to get the ref of an element to handle it directly. Elements support downcasting to
/// Dioxus's virtual element types as well as their true native counterparts. Downcasting to Dioxus' virtual elements
/// will never panic, but downcasting to native elements will fail if on an unsupported platform. We recommend avoiding
/// publishing hooks and components that deply rely on control over elements using their native `ref`, preferring to
/// use their Dioxus Virtual Element counterpart instead.
// This particular code *will panic* due to the unwrap. Try to avoid these types of patterns.
/// ---------------------------------
/// TODO: Get this to compile properly
/// let div_ref = use_node_ref(&cx);
///
/// cx.render(rsx!{
/// div { ref: div_ref, class: "custom class",
/// button { "click me to see my parent's class"
/// onclick: move |_| if let Some(div_ref) = div_ref {
/// panic!("Div class is {}", div_ref.to_native::<web_sys::Element>().unwrap().class())
/// }
/// }
/// }
/// })
static _example: FC<()> = |cx, props| todo!();
/// Antipattern: publishing components and hooks with all features enabled
/// ----------------------------------------------------------------------
///
/// The `dioxus` crate combines a bunch of useful utilities together (like the rsx! and html! macros, hooks, and more).
/// However, when publishing your custom hook or component, we highly advise using only the `core` feature on the dioxus
/// crate. This makes your crate compile faster, makes it more stable, and avoids bringing in incompatible libraries that
/// might make it not compile on unsupported platforms.
///
/// We don't have a code snippet for this, but just prefer to use this line:
/// dioxus = { version = "*", features = ["core"]}
/// instead of this one:
/// dioxus = { version = "*", features = ["web", "desktop", "full"]}
/// in your Cargo.toml
///
/// This will only include the `core` dioxus crate which is relatively slim and fast to compile and avoids target-specific
/// libraries.
static __example: FC<()> = |cx, props| todo!();
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
AntipatternNoKeys { data: std::collections::HashMap::new() }
AntipatternNestedFragments {}
})
};
-37
View File
@@ -1,37 +0,0 @@
//! Example: The basics of Dioxus
//! ----------------------------
//!
//! This small example covers some of the basics of Dioxus including
//! - Components
//! - Props
//! - Children
//! - the rsx! macro
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div {
Greeting {
name: "Dioxus"
div { "Dioxus is a fun, fast, and portable UI framework for Rust" }
}
}
})
};
#[derive(PartialEq, Props)]
struct GreetingProps {
name: &'static str,
}
static Greeting: FC<GreetingProps> = |cx, props| {
cx.render(rsx! {
div {
h1 { "Hello, {props.name}!" }
p { "Welcome to the Diouxs framework" }
br {}
{cx.children()}
}
})
};
-44
View File
@@ -1,44 +0,0 @@
//! Example: Children
//! -----------------
//!
//! Dioxus supports passing children in from the parent. These children are allocated in the parent and just forced
//! into the child. Components that pass in children may not be safely memoized, though in practice its rare for a
//! change in a parent to not result in a different set of children.
//!
//! In Dioxus, children can *only be a list*. Unlike React, you cannot pass in functions or arbitrary data. This is
//! partially a limitaiton in having static types, but is rather intentional to encourage the use of attributes where
//! arbitrary child data might normally be used. Check out the `function driven children` example for how to adopt your
//! React pattern for Dioxus' semantics.
//!
//! Dioxus will let you use the `children` method more than once - and it's semantically *okay* - but you'll likely
//! ruin your page if you try to clone elements in this way. Under the hood, Dioxus shares a "mounted ID" for each node,
//! and mounting the same VNode in two places will overwrite the first mounted ID. This will likely lead to dead elements.
//!
//! In the future, this might become a runtime error, so consider it an error today.
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div {
Banner {
p { "Some Content1" }
}
Banner {
p { "Some Content2" }
}
}
})
};
pub static Banner: FC<()> = |cx, props| {
cx.render(rsx! {
div {
h1 { "This is a great banner!" }
div { class: "content"
{cx.children()}
}
footer { "Wow, what a great footer" }
}
})
};
-116
View File
@@ -1,116 +0,0 @@
//! Example: Conditional Rendering
//! ------------------------------
//!
//! This example shows how to hide or show elements using conditional rendering.
//!
//! Often times you might want to display a different UI given some sort of condition. This is called "conditonal rendering".
//! In Dioxus, you can perform conditional rendering with optionals or matching.
//!
//! The rsx! and html! macro accepts anything that is `IntoIter<Item = impl IntoVnode>`. Options and Results both implement
//! IntoIter for impl VNode, so you can use option/result for conditional rendering.
use dioxus::prelude::*;
// Convert a boolean conditional into a hide/show
#[derive(PartialEq, Props)]
pub struct MyProps {
should_show: bool,
}
pub static Example0: FC<MyProps> = |cx, props| {
cx.render(rsx! {
div {
{props.should_show.then(|| rsx!{
h1 { "showing the title!" }
})}
}
})
};
// Convert a boolean conditional into an either/or
// Because rsx! is lazy (produces a closure), we cannot use it in two branch arms. To use it in matching/branching, we
// must render it.
//
// Dioxus will let you render any `LazyNodes` into a `VNode` with `cx.render`. `rsx!` also supports the `in cx` syntax
// which will do essentially the same thing as `cx.render`.
//
// In short:
// `rsx!(cx, ...)` is shorthand for `cx.render(rsx!(...))`
#[derive(PartialEq, Props)]
pub struct MyProps1 {
should_show: bool,
}
pub static Example1: FC<MyProps1> = |cx, props| {
cx.render(rsx! {
div {
// With matching
{match props.should_show {
true => cx.render(rsx!(div {"it is true!"})),
false => rsx!(cx, div {"it is false!"}),
}}
// or with just regular conditions
{if props.should_show {
rsx!(cx, div {"it is true!"})
} else {
rsx!(cx, div {"it is false!"})
}}
// or with optional chaining
{
props.should_show
.then(|| rsx!(cx, div {"it is false!"}))
.unwrap_or_else(|| rsx!(cx, div {"it is false!"}))
}
}
})
};
/// Matching can be expanded
#[derive(PartialEq)]
pub enum Color {
Green,
Yellow,
Red,
}
#[derive(PartialEq, Props)]
pub struct MyProps2 {
color: Color,
}
pub static Example2: FC<MyProps2> = |cx, props| {
cx.render(rsx! {
div {
{match props.color {
Color::Green => rsx!(cx, div {"it is Green!"}),
Color::Yellow => rsx!(cx, div {"it is Yellow!"}),
Color::Red => rsx!(cx, div {"it is Red!"}),
}}
}
})
};
pub static Example: FC<()> = |cx, props| {
let should_show = use_state(cx, || false);
let mut color_index = use_state(cx, || 0);
let color = match *color_index % 2 {
2 => Color::Green,
1 => Color::Yellow,
_ => Color::Red,
};
cx.render(rsx! {
div {
button {
onclick: move |_| should_show.set(!*should_show)
"click to toggle showing the examples"
}
button {
onclick: move |_| color_index += 1
"click to for the enxt color"
}
Example0 { should_show: *should_show }
Example1 { should_show: *should_show }
Example2 { color: color }
}
})
};
-37
View File
@@ -1,37 +0,0 @@
use dioxus::prelude::*;
fn main() {}
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div {
}
})
};
// A controlled component:
static ControlledSelect: FC<()> = |cx, props| {
let value = use_state(cx, || String::from("Grapefruit"));
cx.render(rsx! {
select { value: "{value}", onchange: move |evt| value.set(evt.value()),
option { value: "Grapefruit", "Grapefruit"}
option { value: "Lime", "Lime"}
option { value: "Coconut", "Coconut"}
option { value: "Mango", "Mango"}
}
})
};
// TODO - how do uncontrolled things work?
static UncontrolledSelect: FC<()> = |cx, props| {
let value = use_state(cx, || String::new());
cx.render(rsx! {
select {
option { value: "Grapefruit", "Grapefruit"}
option { value: "Lime", "Lime"}
option { value: "Coconut", "Coconut"}
option { value: "Mango", "Mango"}
}
})
};
-44
View File
@@ -1,44 +0,0 @@
//! Example: Web Components & Custom Elements
//! -----------------------------------------
//!
//! Web components are a flavor of html elements that can be user-defined.
//! See: https://www.webcomponents.org for more information.
//!
//! Users who use webcomponents typically don't use Dioxus. However, if you would like to use webcomponents in Dioxus,
//! you can easily create a new custom element with compile-time correct wrappers around the webcomponent.
//!
//! We don't support building new webcomponents with Dioxus, however. :(
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div {
custom_element {
custom_attr: "custom data on custom elements"
}
}
})
};
mod dioxus_elements {
use std::fmt::Arguments;
use dioxus::prelude::DioxusElement;
#[allow(non_camel_case_types)]
pub struct custom_element;
impl DioxusElement for custom_element {
const TAG_NAME: &'static str = "custom_element";
const NAME_SPACE: Option<&'static str> = None;
}
impl custom_element {
pub fn custom_attr<'a>(&self, f: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
f.attr("custom_asttr", val, None, false)
}
}
// Re-export the normal html namespace
pub use dioxus::prelude::dioxus_elements::*;
use dioxus_core::{nodes::Attribute, NodeFactory};
}
-8
View File
@@ -1,8 +0,0 @@
//! Example: Null/None Children
//! ---------------------------
//!
//! This is a simple pattern that allows you to return no elements!
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| cx.render(rsx! { Fragment {} });
-85
View File
@@ -1,85 +0,0 @@
//! Example: Errror Handling
//! ------------------------
//!
//! Error handling in Dioxus comes in a few flavors. Because Dioxus is a Rust project, Options and Results are obviously
//! the go-to way of wrapping possibly-errored data. However, if a component fails to "unwrapping," everything will crash,
//! the page will deadlock, and your users will be sad.
//!
//! So, obviously, you need to handle your errors.
//!
//! Fortunately, it's easy to avoid panics, even during quick prototyping.
//!
//! Here's a few strategies:
//! - Leverage the ability to return "None" and propogate None directly
//! - Instead of propogating "None" manually, use the "?" syntax sugar
//! - Covert Results into Options with .ok()
//! - Manually display a separate screen by matching on Options/Results
//!
//! There *are* plans to add helpful screens for when apps completely panic in WASM. However, you should really try to
//! avoid panicking.
use dioxus::prelude::*;
fn main() {}
/// This is one way to go about error handling (just toss things away with unwrap).
/// However, if you get it wrong, the whole app will crash.
/// This is pretty flimsy.
static App: FC<()> = |cx, props| {
let data = get_data().unwrap();
cx.render(rsx!( div { "{data}" } ))
};
/// This is a pretty verbose way of error handling
/// However, it's still pretty good since we don't panic, just fail to render anything
static App1: FC<()> = |cx, props| {
let data = match get_data() {
Some(data) => data,
None => return None,
};
cx.render(rsx!( div { "{data}" } ))
};
/// This is an even better form of error handling.
/// However, it _does_ make the component go blank, which might not be desirable.
///
/// This type of error handling is good when you have "selectors" that produce Some/None based on some state that's
/// already controlled for higher in the tree. IE displaying a "Username" in a component that should only be shown if
/// a user is logged in.
///
/// Dioxus will throw an error in the console if the None-path is ever taken.
static App2: FC<()> = |cx, props| {
let data = get_data()?;
cx.render(rsx!( div { "{data}" } ))
};
/// This is top-tier error handling since it displays a failure state.
///
/// However, the error is lacking in context.
static App3: FC<()> = |cx, props| match get_data() {
Some(data) => cx.render(rsx!( div { "{data}" } )),
None => cx.render(rsx!( div { "Failed to load data :(" } )),
};
/// For errors that return results, it's possible short-circuit the match-based error handling with `.ok()` which converts
/// a Result<T, V> into an Option<T> and lets you
static App4: FC<()> = |cx, props| {
let data = get_data_err().ok()?;
cx.render(rsx!( div { "{data}" } ))
};
/// This is great error handling since it displays a failure state... with context!
///
/// Hopefully you never need to disply a screen like this. It's rather bad taste
static App5: FC<()> = |cx, props| match get_data_err() {
Ok(data) => cx.render(rsx!( div { "{data}" } )),
Err(c) => cx.render(rsx!( div { "Failed to load data: {c}" } )),
};
// this fetching function produces "nothing"
fn get_data() -> Option<String> {
None
}
// this fetching function produces "nothing"
fn get_data_err() -> Result<String, &'static str> {
Result::Err("Failed!")
}
-51
View File
@@ -1,51 +0,0 @@
//! Example: Fragments
//! ------------------
//!
//! Dioxus can return multiple elements without a container through the use of the VNode called a "Fragment". Fragments do not
//! have a mounted root and are inserted inline with their siblings. There are three ways of creating fragments as outlined
//! in the examples below:
//! - By returning multiple elements in Rsx!
//! - By using the `Fragment` component
//! - By using the fragment() method on the node factory
use dioxus::prelude::*;
// Returning multiple elements with rsx! or html!
static App1: FC<()> = |cx, props| {
cx.render(rsx! {
h1 { }
h2 { }
h3 { }
})
};
// Using the Fragment component
static App2: FC<()> = |cx, props| {
cx.render(rsx! {
Fragment {
div {}
div {}
"asd"
}
})
};
// Using the `fragment` method on the NodeFactory
static App3: FC<()> = |cx, props| {
cx.render(LazyNodes::new(move |fac| {
fac.fragment_from_iter([
fac.text(format_args!("A")),
fac.text(format_args!("B")),
fac.text(format_args!("A")),
fac.text(format_args!("B")),
])
}))
};
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
App1 {}
App2 {}
App3 {}
})
};
-30
View File
@@ -1,30 +0,0 @@
//! Examples: CSS
//! -------------
//!
//! Originally taken from:
//! - https://www.w3schools.com/html/tryit.asp?filename=tryhtml_css_internal
//!
//! Include global styles in your app!
//!
//! You can simply drop in a "style" tag and set the inner contents to your stylesheet.
//! It's slightly more manual than React, but is less magical.
//!
//! A coming update with the assets system will make it possible to include global css from child components.
use dioxus::prelude::*;
const STYLE: &str = r#"
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
"#;
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
head { style { "{STYLE}" } }
body {
h1 {"This is a heading"}
p {"This is a paragraph"}
}
})
};
-38
View File
@@ -1,38 +0,0 @@
//! Example: Inline Styles
//! ----------------------
//!
//! This example shows how to use inline styles in Dioxus components.
//!
//! Inline styles function very similar to regular attributes, just grouped together in "style".
//!
//! Inline styles in Dioxus are more performant than React since we're able to cache attributes and compare by pointers.
//! However, it's still not as performant as cascaded styles. Use with care.
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
head {
style: { background_color: "powderblue" }
}
body {
h1 { style: { color: "blue" }
"This is a heading"
}
p { style: { color: "red" }
"This is a paragraph"
}
}
})
};
// .... technically the rsx! macro is slightly broken at the moment and alows styles not wrapped in style {}
// I haven't noticed any name collisions yet, and am tentatively leaving this behavior in..
// Don't rely on it.
static Example2: FC<()> = |cx, props| {
cx.render(rsx! {
div { color: "red"
"hello world!"
}
})
};
-39
View File
@@ -1,39 +0,0 @@
//! Example: Iterators
//! ------------------
//!
//! This example demonstrates how to use iterators with Dioxus.
//! Iterators must be used through the curly braces item in element bodies.
//! While you might be inclined to `.collect::<>` into Html, Dioxus prefers you provide an iterator that
//! resolves to VNodes. It's more efficient and easier to write than having to `collect` everywhere.
//!
//! This also makes it easy to write "pull"-style iterators that don't have a known size.
//!
//! However, when the size of an iterator needs to be know for display purposes, collecting is fine.
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
let example_data = use_state(cx, || 0);
let v = (0..10).map(|f| {
rsx! {
li { onclick: move |_| example_data.set(f)
"ID: {f}"
ul {
{(0..10).map(|k| rsx!{
li {
"Sub iterator: {f}.{k}"
}
})}
}
}
}
});
cx.render(rsx! {
h3 {"Selected: {example_data}"}
ul {
{v}
}
})
};
-56
View File
@@ -1,56 +0,0 @@
//! Example: Listeners
//! ------------------
//!
//! This example demonstrates the various ways listeners may be used in Dioxus.
//! Listeners may be at most `FnMut` - but not `FnOnce`.
//! Listeners may borrow the lifetime of cx (children and hooks), but not of local (stack) data.
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
ButtonList {}
NonUpdatingEvents {}
DisablePropogation {}
})
};
/// We can use `set_name` in multiple closures; the closures automatically *copy* the reference to set_name.
static ButtonList: FC<()> = |cx, props| {
let name = use_state(cx, || "...?");
let names = ["jack", "jill", "john", "jane"]
.iter()
.map(move |n| rsx!(button { onclick: move |_| name.set(n), "{n}" }));
cx.render(rsx!(
div {
h1 { "Hello, {name}" }
{names}
}
))
};
/// This shows how listeners may be without a visible change in the display.
/// Check the console.
static NonUpdatingEvents: FC<()> = |cx, props| {
rsx!(cx, div {
button {
onclick: move |_| log::info!("Did not cause any updates!")
"Click me to log!"
}
})
};
static DisablePropogation: FC<()> = |cx, props| {
rsx!(cx,
div {
onclick: move |_| log::info!("event propogated to the div!")
button {
onclick: move |evt| {
log::info!("Button will allow propogation");
}
}
}
)
};
-84
View File
@@ -1,84 +0,0 @@
//! Example: Memoization
//! --------------------
//!
//! This example showcases how memoization works in Dioxus.
//!
//! Memoization is the process in which Dioxus skips diffing child components if their props don't change.
//! In React, components are never memoized unless wrapped in `memo` or configured with `shouldComponentUpdate`.
//!
//! Due to the safety guarantees of Rust, we can automatically memoize components in some circumstances. Whenever a
//! component's properties are valid for the `'static` lifetime, Dioxus will automatically compare the props before
//! diffing the component. If the props don't change (according to PartialEq), the component will not be re-rendered.
//!
//! However, if the props use some generics or borrow from their parent, then Dioxus can't safely supress updates,
//! and is forced to render the child. If you think that this behavior is wrong for your usecase, you can implement
//! the memo method yourself, but beware, doing so is UNSAFE and may cause issues if you do it wrong.
//!
//! If you want to gain that little bit extra performance, consider using global state management, signals, or
//! memoized collections like im-rc which are designed for this use case.
use dioxus::prelude::*;
// By default, components with no props are always memoized.
// A props of () is considered empty.
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div { "100% memoized!" }
})
};
// These props do not borrow any content, and therefore can be safely memoized.
// However, the parent *must* create a new string on every render.
// Notice how these props implement PartialEq - this is required for 'static props
#[derive(PartialEq, Props)]
pub struct MyProps1 {
name: String,
}
pub static Example1: FC<MyProps1> = |cx, props| {
cx.render(rsx! {
div { "100% memoized! {props.name}" }
})
};
// These props do not borrow any content, and therefore can be safely memoized.
// In contrast with the `String` example, these props use `Rc<str>` which operates similar to strings in JavaScript.
// These strings cannot be modified, but may be cheaply shared in many places without issue.
#[derive(PartialEq, Props)]
pub struct MyProps2 {
name: std::rc::Rc<str>,
}
pub static Example2: FC<MyProps2> = |cx, props| {
cx.render(rsx! {
div { "100% memoized! {props.name}" }
})
};
// These props *do* borrow any content, and therefore cannot be safely memoized!.
#[derive(PartialEq, Props)]
pub struct MyProps3<'a> {
name: &'a str,
}
// We need to manually specify a lifetime that ensures props and scope (the component's state) share the same lifetime.
// Using the `pub static Example: FC<()>` pattern _will_ specify a lifetime, but that lifetime will be static which might
// not exactly be what you want
fn Example3<'a>(cx: Context<'a>, props: &'a MyProps3) -> DomTree<'a> {
cx.render(rsx! {
div { "Not memoized! {props.name}" }
})
}
// These props *do* borrow any content, and therefore cannot be safely memoized!.
// However, they cannot be compared, so we don't need the PartialEq flag.
#[derive(Props)]
pub struct MyProps4<'a> {
onhandle: &'a dyn Fn(),
}
// We need to manually specify a lifetime that ensures props and scope (the component's state) share the same lifetime.
fn Example4<'a>(cx: Context<'a>, props: &'a MyProps4) -> DomTree<'a> {
cx.render(rsx! {
div { "Not memoized!", onclick: move |_| (props.onhandle)() }
})
}
-12
View File
@@ -1,12 +0,0 @@
use dioxus::prelude::*;
fn main() {}
pub static Example: FC<()> = |cx, props| {
let p = 10;
cx.render(rsx! {
div {
}
})
};
-10
View File
@@ -1,10 +0,0 @@
use dioxus::prelude::*;
fn main() {}
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div {
}
})
};
-39
View File
@@ -1,39 +0,0 @@
//! Example: Spread pattern for Components
//! --------------------------------------
//!
//! Dioxus supports the "spread" pattern for manually building a components properties. This is useful when props
//! are passed down from a parent, or it's more ergonomic to construct props from outside the rsx! macro.
//!
//! To use the spread pattern, simply pass ".." followed by a Rust epxression. This pattern also supports overriding
//! values, using the manual props as the base and then modifying fields specified with non-spread attributes.
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
let props = MyProps {
count: 0,
live: true,
name: "Dioxus",
};
cx.render(rsx! {
Example1 { ..props, count: 10, div {"child"} }
})
};
#[derive(PartialEq, Props)]
pub struct MyProps {
count: u32,
live: bool,
name: &'static str,
}
pub static Example1: FC<MyProps> = |cx, MyProps { count, live, name }| {
cx.render(rsx! {
div {
h1 { "Hello, {name}"}
h3 {"Are we alive? {live}"}
p {"Count is {count}"}
{ cx.children() }
}
})
};
-10
View File
@@ -1,10 +0,0 @@
use dioxus::prelude::*;
fn main() {}
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div {
}
})
};
-38
View File
@@ -1,38 +0,0 @@
//! Example: Suspense
//! -----------------
//! This example demonstrates how the use_suspense hook can be used to load and render asynchronous data. Suspense enables
//! components to wait on futures to complete before rendering the result into VNodes. These VNodes are immediately
//! available in a suspended" fashion and will automatically propogate to the UI when the future completes.
//!
//! Currently, suspense futures are non-restartable. In the future, we'll provide more granular control of how to start,
//! stop, and reset these futures.
use dioxus::prelude::*;
#[derive(serde::Deserialize)]
struct DogApi {
message: String,
}
const ENDPOINT: &str = "https://dog.ceo/api/breeds/image/random";
pub static Example: FC<()> = |cx, props| {
let doggo = use_suspense(
cx,
|| surf::get(ENDPOINT).recv_json::<DogApi>(),
|cx, res| match res {
Ok(res) => rsx!(
cx,
img {
src: "{res.message}"
}
),
Err(_) => rsx!(cx, div { "No doggos for you :(" }),
},
);
cx.render(rsx!(
div {
h1 {"Waiting for a doggo..."}
{doggo}
}
))
};
-61
View File
@@ -1,61 +0,0 @@
//! Example: Tasks
//! --------------
//!
//! Built around the same system that powers suspense, Dioxus also allows users to write arbitrary tasks that can modify
//! state asynchronously. `use_task` takes a future and returns a task handle and an option that holds the tasks's return
//! value. When the task completes, the component will re-render with the result freshly available.
//!
//! Tasks don't necessarily need to complete, however. It would be completely reasonable to wire up a websocket receiver
//! in a task and have it work infinitely while the app is running. If the socket throws an error, the task could complete
//! and the UI could present a helpful error message.
//!
//! Tasks also return the `TaskHandle` type which lets other component logic start, stop, and restart the task at any time.
//! Tasks are very much like an async-flavoroued coroutine, making them incredibly powerful.
//!
//! Tasks must be valid for the 'static lifetime, so any state management neeeds to be cloned into the closure. `use_state`
//! has a method called `for_async` which generates an AsyncUseState wrapper. This has a very similar API to the regualr
//! `use_state` but is `static.
//!
//! Remeber `use_task` is a hook! Don't call it out of order or in loops. You might aaccidentally swap the task handles
//! and break things in subtle ways.
//!
//! Whenever a component is scheduled for deletion, the task is dropped. Make sure that whatever primitives used in the
//! task have a valid drop implementation and won't leave resources tied up.
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
let count = use_state(cx, || 0);
let mut direction = use_state(cx, || 1);
// Tasks are 'static, so we need to copy relevant items in
let (async_count, dir) = (count.for_async(), *direction);
let (task, result) = use_task(cx, move || async move {
loop {
gloo_timers::future::TimeoutFuture::new(250).await;
*async_count.get_mut() += dir;
}
});
cx.render(rsx! {
div {
h1 {"count is {count}"}
button {
"Stop counting"
onclick: move |_| task.stop()
}
button {
"Start counting"
onclick: move |_| task.resume()
}
button {
"Switch counting direcion"
onclick: move |_| {
direction *= -1;
task.restart();
}
}
}
})
};
-9
View File
@@ -1,9 +0,0 @@
use dioxus::prelude::*;
pub static Example: FC<()> = |cx, props| {
cx.render(rsx! {
div {
}
})
};
-25
View File
@@ -1,25 +0,0 @@
use dioxus::prelude::*;
use dioxus::ssr;
pub static Example: FC<()> = |cx, props| {
let as_string = use_state(cx, || {
// Currently, SSR is only supported for whole VirtualDOMs
// This is an easy/low hanging fruit to improve upon
let mut dom = VirtualDom::new(SomeApp);
dom.rebuild();
ssr::render_vdom(&dom, |c| c)
});
cx.render(rsx! {
div { "{as_string}" }
})
};
static SomeApp: FC<()> = |cx, props| {
cx.render(rsx! {
div { style: {background_color: "blue"}
h1 {"Some amazing app or component"}
p {"Things are great"}
}
})
};