Rework Guide (#486)

* Move getting started to Guide

* Clean up summary and getting started

* Shorten intro by moving stuff to individual platform docs

* Make intro even shorter, summarize features

* Further cleanup; move development-related docs to separate section

* Make `guide` a crate. Turn code samples into examples so that we can check if they compile

* Rewrite "Describing the UI":

* Focus on RSX syntax (interactivity covered in later chapters); make sure samples are tested; concise language

* Move some "special attribute" samples to the `examples` directory

* Simplify introduction to components

* Simplify introduction to component props

* Document Prop features; add code samples

* Simplify component children docs

* Interactivity: better introduction to events

* Hooks: better introduction

* Remove outdated doc

* Introducs use_ref

* Simplify User Input chapter

* Document event handler props

* Meme editor example

* Meme editor walkthrough

* Add dark mode example

* Guide for context; dark mode example

* Guide: custom hooks

* Guide: conditional rendering

* Guide: rendering lists

* Guide: rendering lists + keys

* Move remaining infor from Reference to guide

* Delete reference book
This commit is contained in:
Reinis Mazeiks authored and GitHub committed 2022-07-07 08:50:36 +00:00
1 parent 92a8b7c75f
commit 6c323e9fc5
152 files changed
+2827 -5052

No files matched your search

-185
View File
@@ -1,185 +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 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
//! - Understanding 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, stable ID 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>,
}
fn AntipatternNoKeys(cx: Scope<NoKeysProps>) -> Element {
// WRONG: Make sure to add keys!
cx.render(rsx! {
ul {
cx.props.data.iter().map(|(k, v)| rsx!(li { "List item: {v}" }))
}
});
// RIGHT: Like this:
cx.render(rsx! {
ul {
cx.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 deeply 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.
fn AntipatternNestedFragments(cx: Scope<()>) -> Element {
// Try to avoid heavily nesting fragments
cx.render(rsx!(
Fragment {
Fragment {
Fragment {
Fragment {
Fragment {
div { "Finally have a real node!" }
}
}
}
}
}
))
}
/// Antipattern: Using state after it's 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.
fn AntipatternRelyingOnSetState(cx: Scope) -> Element {
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 misuses. In short:
/// - Only raw elements may start with a lowercase character
/// - All components must start with an uppercase character
///
/// i.e.: the following component will be rejected when attempted to be used in the rsx! macro
static antipattern_component: Component = |cx| todo!();
/// Antipattern: Misusing hooks
/// ---------------------------
///
/// This pattern is an unfortunate one where Dioxus replicates the same behavior as other frameworks. Dioxus supports
/// "hooks" - i.e. "memory cells" that allow a value to be stored between renders. This allows other hooks to tap into
/// a component's "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 misused:
/// - 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 to the same data between renders. This is validated by TypeId and, eventually, a custom key.
#[derive(PartialEq, Props)]
struct MisuedHooksProps {
should_render_state: bool,
}
fn AntipatternMisusedHooks(cx: Scope<MisuedHooksProps>) -> Element {
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();
cx.render(rsx!(div { "{state}" }))
} else {
cx.render(rsx!(div { "Not rendering state" }))
}
}
/// Antipattern: Downcasting refs and panicking
/// ------------------------------------------
///
/// Occasionally it's useful to get the ref of an element to handle it directly. Elements support downcasting to
/// Dioxus' 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 deeply rely on controlling 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: Component = |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: Component = |cx| todo!();
fn Example(cx: Scope) -> Element {
cx.render(rsx! {
AntipatternNoKeys { data: std::collections::HashMap::new() }
AntipatternNestedFragments {}
})
}
-38
View File
@@ -1,38 +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 fn Example(cx: Scope) -> Element {
cx.render(rsx! {
div {
Greeting {
name: "Dioxus"
div { "Dioxus is a fun, fast, and portable UI framework for Rust" }
}
}
})
}
#[derive(PartialEq, Props)]
struct GreetingProps<'a> {
name: &'static str,
children: Element<'a>,
}
pub fn Greeting<'a>(cx: Scope<'a, GreetingProps<'a>>) -> Element {
cx.render(rsx! {
div {
h1 { "Hello, {cx.props.name}!" }
p { "Welcome to the Dioxus framework" }
br {}
&cx.props.children
}
})
}
-47
View File
@@ -1,47 +0,0 @@
//! Example: Children
//! -----------------
//!
//! Dioxus supports passing children in from the parent. These children are allocated in the parent and just passed
//! into the child. Components that pass in children may not be safely memoized, though in practice it's 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 limitation of 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 to 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 Example(cx: Scope) -> Element {
cx.render(rsx! {
div {
Banner {
p { "Some Content1" }
}
Banner {
p { "Some Content2" }
}
}
})
}
#[derive(Props)]
struct BannerProps<'a> {
children: Element<'a>,
}
fn Banner<'a>(cx: Scope<'a, BannerProps<'a>>) -> Element<'a> {
cx.render(rsx! {
div {
h1 { "This is a great banner!" }
div { class: "content", &cx.props.children }
footer { "Wow, what a great footer" }
}
})
}
@@ -1,114 +0,0 @@
//! Example: Conditional Rendering
//! ------------------------------
//!
//! This example shows how to hide or show elements using conditional rendering.
//!
//! Oftentimes you might want to display a different UI given some sort of condition. This is called "conditional rendering".
//! In Dioxus, you can perform conditional rendering with optionals or matching.
//!
//! The rsx! and html! macros 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 fn Example0(cx: Scope<MyProps>) -> Element {
cx.render(rsx! {
div {
cx.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 fn Example1(cx: Scope<MyProps1>) -> Element {
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 true!"}))
.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 fn Example2(cx: Scope<MyProps2>) -> Element {
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 fn Example(cx: Scope<()>) -> Element {
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 }
}
})
}
@@ -1,37 +0,0 @@
use dioxus::prelude::*;
fn main() {}
pub fn Example(cx: Scope) -> Element {
cx.render(rsx! {
div {
}
})
}
// A controlled component:
pub fn ControlledSelect(cx: Scope) -> Element {
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?
pub fn UncontrolledSelect(cx: Scope) -> Element {
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"}
}
})
}
-10
View File
@@ -1,10 +0,0 @@
//! Example: Null/None Children
//! ---------------------------
//!
//! This is a simple pattern that allows you to return no elements!
use dioxus::prelude::*;
pub fn Example(cx: Scope) -> Element {
None
}
-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::*;
pub fn Example(cx: Scope) -> Element {
cx.render(rsx! {
App1 {}
App2 {}
App3 {}
})
}
// Returning multiple elements with rsx! or html!
pub fn App1(cx: Scope) -> Element {
cx.render(rsx! {
h1 { }
h2 { }
h3 { }
})
}
// Using the Fragment component
pub fn App2(cx: Scope) -> Element {
cx.render(rsx! {
Fragment {
div {}
div {}
"asd"
}
})
}
// Using the `fragment` method on the NodeFactory
pub fn App3(cx: Scope) -> Element {
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")),
])
}))
}
-34
View File
@@ -1,34 +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 known for display purposes, collecting is fine.
use dioxus::prelude::*;
pub static Example: Component = |cx| {
let example_data = use_state(&cx, || 0);
cx.render(rsx! {
h3 {"Selected: {example_data}"}
ul {
(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}" }
})
}
}
})
}
})
};
-55
View File
@@ -1,55 +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 fn Example(cx: Scope) -> Element {
cx.render(rsx! {
ButtonList {}
NonUpdatingEvents {}
DisablePropagation {}
})
}
/// We can use `set_name` in multiple closures; the closures automatically *copy* the reference to set_name.
pub fn ButtonList(cx: Scope) -> Element {
let name = use_state(&cx, || "...?");
cx.render(rsx!(
div {
h1 { "Hello, {name}" }
["jack", "jill", "john", "jane"]
.iter()
.map(move |n| rsx!(button { onclick: move |_| name.set(n), "{n}" }))
}
))
}
/// This shows how listeners may be without a visible change in the display.
/// Check the console.
pub fn NonUpdatingEvents(cx: Scope) -> Element {
cx.render(rsx! {
div {
button {
onclick: move |_| log::trace!("Did not cause any updates!"),
"Click me to log!"
}
}
})
}
pub fn DisablePropagation(cx: Scope) -> Element {
cx.render(rsx! {
div {
onclick: move |_| log::trace!("event propagated to the div!")
button {
onclick: move |evt| log::trace!("Button will allow propagation"),
}
}
})
}