docs: examples

This commit is contained in:
Jonathan Kelley committed 2021-07-02 01:30:52 -04:00
1 parent 818043e5e4
commit d9e6d0925b
33 files changed
+732 -152

No files matched your search

+176
View File
@@ -0,0 +1,176 @@
//! 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::*;
fn main() {}
/// 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| {
// WRONG: Make sure to add keys!
rsx!(in cx, ul {
{cx.data.iter().map(|(k, v)| rsx!(li { "List item: {v}" }))}
});
// RIGHT: Like this:
rsx!(in cx, ul {
{cx.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| {
// Try to avoid heavily nesting fragments
rsx!(in 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| {
let (state, set_state) = use_state(&cx, || "Hello world");
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| 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| {
if cx.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");
rsx!(in cx, div { "{state}" })
} else {
rsx!(in 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| 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| todo!();
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+45
View File
@@ -0,0 +1,45 @@
//! 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::*;
fn main() {}
static App: FC<()> = |cx| {
cx.render(rsx! {
div {
Banner {
p { "Some Content1" }
}
Banner {
p { "Some Content2" }
}
}
})
};
static Banner: FC<()> = |cx| {
cx.render(rsx! {
div {
h1 { "This is a great banner!" }
div { class: "content"
{cx.children()}
}
footer { "Wow, what a great footer" }
}
})
};
@@ -0,0 +1,92 @@
//! 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::*;
fn main() {}
// Convert a boolean conditional into a hide/show
#[derive(PartialEq, Props)]
struct MyProps {
should_show: bool,
}
static Example: FC<MyProps> = |cx| {
cx.render(rsx! {
div {
{cx.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!(in cx, ...)` is shorthand for `cx.render(rsx!(...))`
#[derive(PartialEq, Props)]
struct MyProps1 {
should_show: bool,
}
static Example1: FC<MyProps1> = |cx| {
cx.render(rsx! {
div {
// With matching
{match cx.should_show {
true => cx.render(rsx!(div {"it is true!"})),
false => rsx!(in cx, div {"it is false!"}),
}}
// or with just regular conditions
{if cx.should_show {
rsx!(in cx, div {"it is true!"})
} else {
rsx!(in cx, div {"it is false!"})
}}
// or with optional chaining
{
cx.should_show
.then(|| rsx!(in cx, div {"it is false!"}))
.unwrap_or_else(|| rsx!(in cx, div {"it is false!"}))
}
}
})
};
/// Matching can be expanded
#[derive(PartialEq)]
enum Color {
Green,
Yellow,
Red,
}
#[derive(PartialEq, Props)]
struct MyProps2 {
color: Color,
}
static Example2: FC<MyProps2> = |cx| {
cx.render(rsx! {
div {
{match cx.color {
Color::Green => rsx!(in cx, div {"it is Green!"}),
Color::Yellow => rsx!(in cx, div {"it is Yellow!"}),
Color::Red => rsx!(in cx, div {"it is Red!"}),
}}
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+15
View File
@@ -0,0 +1,15 @@
//! Example: Null/None Children
//! ---------------------------
//!
//! This is a simple pattern that allows you to return no elements!
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+45
View File
@@ -0,0 +1,45 @@
//! 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::*;
fn main() {}
// Returning multiple elements with rsx! or html!
static Example1: FC<()> = |cx| {
cx.render(rsx! {
h1 { }
h2 { }
h3 { }
// {}
// "hello world"
})
};
// Using the Fragment component
static Example2: FC<()> = |cx| {
cx.render(rsx! {
Fragment {
div {}
div {}
"asd"
}
})
};
// Using the `fragment` method on the NodeFactory
static Example3: FC<()> = |cx| {
cx.render(LazyNodes::new(move |fac: &NodeFactory| {
fac.fragment_builder(None, |list| {
list.add_child(fac.text(format_args!("A")))
.add_child(fac.text(format_args!("B")))
.finish()
})
}))
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+50
View File
@@ -0,0 +1,50 @@
//! 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::*;
fn main() {}
/// We can use `set_name` in multiple closures; the closures automatically *copy* the reference to set_name.
static ButtonList: FC<()> = |cx| {
let (name, set_name) = use_state(&cx, || "...?");
let names = ["jack", "jill", "john", "jane"]
.iter()
.map(move |n| rsx!(button { onclick: move |_| set_name(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| {
rsx!(in cx, div {
button {
onclick: move |_| log::info!("Did not cause any updates!")
"Click me to log!"
}
})
};
static DisablePropogation: FC<()> = |cx| {
rsx!(in cx,
div {
onclick: move |_| log::info!("event propogated to the div!")
button {
onclick: move |evt| {
log::info!("Button will allow propogation");
}
}
}
)
};
+85
View File
@@ -0,0 +1,85 @@
//! 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::*;
fn main() {}
// By default, components with no props are always memoized.
// A props of () is considered empty.
static Example: FC<()> = |cx| {
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)]
struct MyProps1 {
name: String,
}
static Example1: FC<MyProps1> = |cx| {
cx.render(rsx! {
div { "100% memoized! {cx.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)]
struct MyProps2 {
name: std::rc::Rc<str>,
}
static Example2: FC<MyProps2> = |cx| {
cx.render(rsx! {
div { "100% memoized! {cx.name}" }
})
};
// These props *do* borrow any content, and therefore cannot be safely memoized!.
#[derive(PartialEq, Props)]
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 `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, MyProps3<'a>>) -> VNode {
cx.render(rsx! {
div { "Not memoized! {cx.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)]
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, MyProps4<'a>>) -> VNode {
cx.render(rsx! {
div { "Not memoized!", onclick: move |_| (cx.onhandle)() }
})
}
+2
View File
@@ -0,0 +1,2 @@
mod iterator;
mod memo;
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+40
View File
@@ -0,0 +1,40 @@
//! 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::*;
fn main() {}
static App: FC<()> = |cx| {
let props = MyProps {
count: 0,
live: true,
name: "Dioxus",
};
cx.render(rsx! {
Example { ..props, count: 10, div {"child"} }
})
};
#[derive(PartialEq, Props)]
struct MyProps {
count: u32,
live: bool,
name: &'static str,
}
static Example: FC<MyProps> = |cx| {
cx.render(rsx! {
div {
h1 { "Hello, {cx.name}"}
h3 {"Are we alive? {cx.live}"}
p {"Count is {cx.count}"}
{ cx.children() }
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+59
View File
@@ -0,0 +1,59 @@
//! Example: Suspense
//! -----------------
//! This example shows how the "use_fetch" hook is built on top of Dioxus' "suspense" API. 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.
//!
//! Note that if your component updates or receives new props while it is awating the result, the future will be dropped
//! and all work will stop. In this example, we store the future in a hook so we can always resume it.
use dioxus::prelude::*;
fn main() {}
#[derive(serde::Deserialize)]
struct DogApi {
message: String,
}
const ENDPOINT: &str = "https://dog.ceo/api/breeds/image/random";
pub static App: FC<()> = |cx| {
let doggo = use_future_effect(&cx, move || async move {
match surf::get(ENDPOINT).recv_json::<DogApi>().await {
Ok(res) => rsx!(in cx, img { src: "{res.message}" }),
Err(_) => rsx!(in cx, div { "No doggos for you :(" }),
}
});
cx.render(rsx!(
div {
h1 {"Waiting for a doggo..."}
{doggo}
}
))
};
use dioxus_core::virtual_dom::SuspendedContext;
use futures::Future;
use futures::FutureExt;
use std::pin::Pin;
fn use_fetch<'a, T: serde::de::DeserializeOwned + 'static>(
cx: &impl Scoped<'a>,
url: &str,
g: impl FnOnce(SuspendedContext, surf::Result<T>) -> VNode<'a> + 'a,
) -> VNode<'a> {
// essentially we're doing a "use_effect" but with no dependent props or post-render shenanigans
let fetch_promise = cx.use_hook(
move || surf::get(url).recv_json::<T>().boxed_local(),
// just pass the future through
|p| p,
|_| (),
);
cx.suspend(fetch_promise, g)
}
/// Spawns the future only when the inputs change
fn use_future_effect<'a, 'b, F: Future<Output = VNode<'b>>>(
cx: &impl Scoped<'a>,
g: impl FnOnce() -> F + 'a,
) -> VNode<'a> {
todo!()
}
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+10
View File
@@ -0,0 +1,10 @@
use dioxus::prelude::*;
fn main() {}
static Example: FC<()> = |cx| {
cx.render(rsx! {
div {
}
})
};
+21
View File
@@ -0,0 +1,21 @@
//! Example: Web Components
//! -----------------------
//!
//! 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::{builder::ElementBuilder, prelude::NodeFactory};
fn main() {}
// TODO
struct MyEle<'a, 'b> {
el: ElementBuilder<'a, 'b>,
fac: &'b NodeFactory<'a>,
}