Fix various typos and grammar nits

I also removed all trailing whitespace from lines since I have Emacs
configured to highlight this.
This commit is contained in:
Dave Rolsky 2022-01-21 21:43:43 -06:00
parent 63b06b7977
commit 9e4ec43b1e
39 changed files with 160 additions and 161 deletions

View file

@ -84,7 +84,7 @@ If you know React, then you already know Dioxus.
- Comprehensive inline documentation - hover and guides for all HTML elements, listeners, and events.
- Extremely memory efficient - 0 global allocations for steady-state components.
- Multi-channel asynchronous scheduler for first-class async support.
- And more! Read the [full release post here](https://dioxuslabs.com/blog/introducing-dioxus/).
- And more! Read the [full release post](https://dioxuslabs.com/blog/introducing-dioxus/).
### Examples
@ -121,9 +121,9 @@ See the [awesome-dioxus](https://github.com/DioxusLabs/awesome-dioxus) page for
## Why Dioxus and why Rust?
TypeScript is a fantastic addition to JavaScript, but it's still fundamentally JavaScript. TS code runs slightly slower, has tons of configuration options, and not every package is properly typed.
TypeScript is a fantastic addition to JavaScript, but it's still fundamentally JavaScript. TS code runs slightly slower, has tons of configuration options, and not every package is properly typed.
In contrast, Dioxus is written in Rust - which is almost like "TypeScript on steroids".
In contrast, Dioxus is written in Rust - which is almost like "TypeScript on steroids".
By using Rust, we gain:
@ -141,12 +141,12 @@ By using Rust, we gain:
Specifically, Dioxus provides us many other assurances:
- Proper use of immutable datastructures
- Guaranteed error handling (so you can sleep easy at night not worrying about `cannot read property of undefined`)
- Proper use of immutable data structures
- Guaranteed error handling (so you can sleep easy at night not worrying about `cannot read property of undefined`)
- Native performance on mobile
- Direct access to system IO
And much more. Dioxus makes Rust apps just as fast to write as React apps, but affords more robustness, giving your frontend team greater confidence in making big changes in shorter time.
And much more. Dioxus makes Rust apps just as fast to write as React apps, but affords more robustness, giving your frontend team greater confidence in making big changes in shorter time.
### Why NOT Dioxus?
You shouldn't use Dioxus if:
@ -154,13 +154,13 @@ You shouldn't use Dioxus if:
- You don't like the React Hooks approach to frontend
- You need a no-std renderer
- You want to support browsers where Wasm or asm.js are not supported.
- You need a Send+Sync UI solution (Dioxus is not currently ThreadSafe)
- You need a Send+Sync UI solution (Dioxus is not currently thread-safe)
### Comparison with other Rust UI frameworks
Dioxus primarily emphasizes **developer experience** and **familiarity with React principles**.
Dioxus primarily emphasizes **developer experience** and **familiarity with React principles**.
- [Yew](https://github.com/yewstack/yew): prefers the elm pattern instead of React-hooks, no borrowed props, supports SSR (no hydration).
- [Percy](https://github.com/chinedufn/percy): Supports SSR but less emphasis on state management and event handling.
- [Percy](https://github.com/chinedufn/percy): Supports SSR but with less emphasis on state management and event handling.
- [Sycamore](https://github.com/sycamore-rs/sycamore): VDOM-less using fine-grained reactivity, but lacking in ergonomics.
- [Dominator](https://github.com/Pauan/rust-dominator): Signal-based zero-cost alternative, less emphasis on community and docs.

View file

@ -22,7 +22,7 @@ In general, Dioxus and React share many functional similarities. If this guide i
## Multiplatform
Dioxus is a *portable* toolkit, meaning the Core implementation can run anywhere with no platform-dependent linking. Unlike many other Rust frontend toolkits, Dioxus is not intrinsically linked to Web-Sys. In fact, every element and event listener can be swapped out at compile time. By default, Dioxus ships with the `Html` feature enabled which can be disabled depending on your target renderer.
Dioxus is a *portable* toolkit, meaning the Core implementation can run anywhere with no platform-dependent linking. Unlike many other Rust frontend toolkits, Dioxus is not intrinsically linked to Web-Sys. In fact, every element and event listener can be swapped out at compile time. By default, Dioxus ships with the `html` feature enabled, but this can be disabled depending on your target renderer.
Right now, we have several 1st-party renderers:
- WebSys (for WASM)
@ -33,8 +33,7 @@ Right now, we have several 1st-party renderers:
### Web Support
---
The Web is the most-supported target platform for Dioxus. To run on the Web, your app must be compiled to WebAssembly and depend on the `dioxus` crate with the `web` feature enabled. Because of the Wasm limitation, not every crate will work with your web-apps, so you'll need to make sure that your crates work without native system calls (timers, IO, etc).
The Web is the best-supported target platform for Dioxus. To run on the Web, your app must be compiled to WebAssembly and depend on the `dioxus` crate with the `web` feature enabled. Because of the limitations of Wasm not every crate will work with your web-apps, so you'll need to make sure that your crates work without native system calls (timers, IO, etc).
Because the web is a fairly mature platform, we expect there to be very little API churn for web-based features.
@ -45,9 +44,10 @@ Examples:
- [ECommerce](https://github.com/DioxusLabs/example-projects/tree/master/ecommerce-site)
[![TodoMVC example](https://github.com/DioxusLabs/example-projects/raw/master/todomvc/example.png)](https://github.com/DioxusLabs/example-projects/blob/master/todomvc)
### SSR Support
---
Dioxus supports server-side rendering!
Dioxus supports server-side rendering!
For rendering statically to an `.html` file or from a WebServer, then you'll want to make sure the `ssr` feature is enabled in the `dioxus` crate and use the `dioxus::ssr` API. We don't expect the SSR API to change drastically in the future.
@ -90,13 +90,13 @@ Examples:
### LiveView / Server Component Support
---
The internal architecture of Dioxus was designed from day one to support the `LiveView` use-case, where a web server hosts a running app for each connected user. As of today, there is no first-class LiveView support - you'll need to wire this up yourself.
The internal architecture of Dioxus was designed from day one to support the `LiveView` use-case, where a web server hosts a running app for each connected user. As of today, there is no first-class LiveView support - you'll need to wire this up yourself.
While not currently fully implemented, the expectation is that LiveView apps can be a hybrid between Wasm and server-rendered where only portions of a page are "live" and the rest of the page is either server-rendered, statically generated, or handled by the host SPA.
### Multithreaded Support
---
The Dioxus VirtualDom, sadly, is not currently `Send`. Internally, we use quite a bit of interior mutability which is not thread-safe. This means you can't easily use Dioxus with most web frameworks like Tide, Rocket, Axum, etc.
The Dioxus VirtualDom, sadly, is not currently `Send`. Internally, we use quite a bit of interior mutability which is not thread-safe. This means you can't easily use Dioxus with most web frameworks like Tide, Rocket, Axum, etc.
To solve this, you'll want to spawn a VirtualDom on its own thread and communicate with it via channels.

View file

@ -1,7 +1,7 @@
# Summary
- [Introduction](README.md)
- [Getting Setup](setup.md)
- [Getting Set Up](setup.md)
- [Hello, World!](hello_world.md)
- [Describing the UI](elements/index.md)
- [Intro to Elements](elements/vnodes.md)
@ -17,8 +17,8 @@
- [User Input and Controlled Components](interactivity/user_input.md)
- [Lifecycle, updates, and effects](interactivity/lifecycles.md)
- [Managing State](state/index.md)
- [Local State](state/localstate.md)
- [Lifting State](state/liftingstate.md)
- [Local State](state/localstate.md)
- [Lifting State](state/liftingstate.md)
- [Global State](state/sharedstate.md)
- [Error handling](state/errorhandling.md)
- [Working with Async](async/index.md)

View file

@ -1,6 +1,6 @@
# Core Topics
In this chapter, we'll cover some core topics on how Dioxus works and how to best leverage the features to build a beautiful, reactive app.
In this chapter, we'll cover some core topics about how Dioxus works and how to best leverage the features to build a beautiful, reactive app.
At a very high level, Dioxus is simply a Rust framework for _declaring_ user interfaces and _reacting_ to changes.

View file

@ -33,9 +33,9 @@ async fetch_name() -> String {
This component will only schedule its render once the fetch is complete. However, we _don't_ recommend using async/await directly in your components.
Async is a notoriously challenging yet rewarding tool for efficient tools. If not careful, locking and unlocking shared aspects of the component's context can lead to data races and panics. If a shared resource is locked while the component is awaiting, then other components can be locked or panic when trying to access the same resource. These rules are especially important when references to shared global state are accessed using the context object's lifetime. If mutable references to data captured immutably by the context are taken, then the component will panic, and cause confusion.
Async is a notoriously challenging yet rewarding tool for efficient tools. If not careful, locking and unlocking shared aspects of the component's context can lead to data races and panics. If a shared resource is locked while the component is awaiting, then other components can be locked or panic when trying to access the same resource. These rules are especially important when references to shared global state are accessed using the context object's lifetime. If mutable references to data captured immutably by the context are taken, then the component will panic, causing confusion.
Instead, we suggest using hooks and future combinators that can safely utilize the safe guards of the component's Context when interacting with async tasks.
Instead, we suggest using hooks and future combinators that can safely utilize the safeguards of the component's Context when interacting with async tasks.
As part of our Dioxus hooks crate, we provide a data loader hook which pauses a component until its async dependencies are ready. This caches requests, reruns the fetch if dependencies have changed, and provides the option to render something else while the component is loading.

View file

@ -2,13 +2,13 @@
Dioxus differs slightly from other UI virtual doms in some subtle ways due to its memory allocator.
One important aspect to understand is how props are passed down from parent components to children. All "components" (custom user-made UI elements) are tightly allocated together in an arena. However, because props and hooks are generically typed, they are casted to any and allocated on the heap - not in the arena with the components.
One important aspect to understand is how props are passed down from parent components to children. All "components" (custom user-made UI elements) are tightly allocated together in an arena. However, because props and hooks are generically typed, they are casted to `Any` and allocated on the heap - not in the arena with the components.
With this system, we try to be more efficient when leaving the component arena and entering the heap. By default, props are memoized between renders using COW and context. This makes props comparisons fast - done via ptr comparisons on the cow pointer. Because memoization is done by default, parent re-renders will _not_ cascade to children if the child's props did not change.
https://dmitripavlutin.com/use-react-memo-wisely/
This behavior is defined as an implicit attribute to user components. When in React land you might wrap a component is `react.memo`, Dioxus components are automatically memoized via an implicit attribute. You can manually configure this behavior on any component with "nomemo" to disable memoization.
This behavior is defined as an attribute implicit to user components. When in React land you might wrap a component with `react.memo`, Dioxus components are automatically memoized via an implicit attribute. You can manually configure this behavior on any component with "nomemo" to disable memoization.
```rust
fn test() -> DomTree {
@ -40,7 +40,7 @@ fn test_component(cx: Scope, name: String) -> Element {
"This is different than React, why differ?".
Take a component likes this:
Take a component like this:
```rust
fn test(cx: Scope) -> DomTree {
@ -55,4 +55,4 @@ fn test(cx: Scope) -> DomTree {
}
```
While the contents of the destructured bundle might change, not every child component will need to be re-rendered.
While the contents of the destructured bundle might change, not every child component will need to be re-rendered every time the context changes.

View file

@ -1,6 +1,6 @@
# Signals: Skipping the Diff
In most cases, the traditional VirtualDOM diffing pattern is plenty fast. Dioxus will compare trees of VNodes, find the differences, and then update the Renderer's DOM with the updates. However, this can generate a lot of overhead for certain types of components. In apps where reducing visual latency is a top priority, you can opt into the `Signals` api to entirely disable diffing of hot-path components. Dioxus will then automatically construct a state machine for your component, making updates nearly instant.
In most cases, the traditional VirtualDOM diffing pattern is plenty fast. Dioxus will compare trees of VNodes, find the differences, and then update the Renderer's DOM with the diffs. However, this can generate a lot of overhead for certain types of components. In apps where reducing visual latency is a top priority, you can opt into the `Signals` api to entirely disable diffing of hot-path components. Dioxus will then automatically construct a state machine for your component, making updates nearly instant.
Signals build on the same infrastructure that powers asynchronous rendering where in-tree values can be updated outside of the render phase. In async rendering, a future is used as the signal source. With the raw signal API, any value can be used as a signal source.
@ -69,7 +69,7 @@ fn Calculator(cx: Scope) -> DomTree {
}
```
Do you notice how we can use built-in operations on signals? Under the hood, we actually create a new derived signal that depends on `a` and `b`. Whenever `a` or `b` update, then `c` will update. If we need to create a new derived signal that's more complex that a basic operation (`std::ops`) we can either chain signals together or combine them:
Do you notice how we can use built-in operations on signals? Under the hood, we actually create a new derived signal that depends on `a` and `b`. Whenever `a` or `b` update, then `c` will update. If we need to create a new derived signal that's more complex than a basic operation (`std::ops`) we can either chain signals together or combine them:
```rust
let mut a = use_signal(&cx, || 0);
@ -88,7 +88,7 @@ let mut a = use_signal(&cx, || 0);
let c = *a + *b;
```
Calling `deref` or `derefmut` is actually more complex than it seems. When a value is derefed, you're essentially telling Dioxus that _this_ element _needs_ to be subscribed to the signal. If a signal is derefed outside of an element, the entire component will be subscribed and the advantage of skipping diffing will be lost. Dioxus will throw an error in the console when this happens to tell you that you're using signals wrong, but your component will continue to work.
Calling `deref` or `deref_mut` is actually more complex than it seems. When a value is derefed, you're essentially telling Dioxus that _this_ element _needs_ to be subscribed to the signal. If a signal is derefed outside of an element, the entire component will be subscribed and the advantage of skipping diffing will be lost. Dioxus will throw an error in the console when this happens to tell you that you're using signals wrong, but your component will continue to work.
## Global Signals
@ -128,7 +128,7 @@ Sometimes you want to use a collection of items. With Signals, you can bypass di
By default, Dioxus is limited when you use iter/map. With the `For` component, you can provide an iterator and a function for the iterator to map to.
Dioxus automatically understands how to use your signals when mixed with iterators through Deref/DerefMut. This lets you efficiently map collections while avoiding the re-rendering of lists. In essence, signals act as a hint to Dioxus on how to avoid un-necessary checks and renders, making your app faster.
Dioxus automatically understands how to use your signals when mixed with iterators through `Deref`/`DerefMut`. This lets you efficiently map collections while avoiding the re-rendering of lists. In essence, signals act as a hint to Dioxus on how to avoid un-necessary checks and renders, making your app faster.
```rust
const DICT: AtomFamily<String, String> = |_| {};

View file

@ -6,7 +6,7 @@ For a VirtualDom that has a root tree with two subtrees, the edits follow a patt
Root
-> Tree 1
-> Tree 2
-> Tree 2
-> Original root tree
- Root edits
@ -39,7 +39,7 @@ fn Window() -> DomTree {
onassign: move |e| {
// create window
}
children()
children()
}
}

View file

@ -20,7 +20,7 @@ For reference, check out the WebSys renderer as a starting point for your custom
## Trait implementation and DomEdits
The current `RealDom` trait lives in `dioxus_core/diff`. A version of it is provided here (but might not be up-to-date):
The current `RealDom` trait lives in `dioxus-core/diff`. A version of it is provided here (but might not be up-to-date):
```rust
pub trait RealDom<'a> {

View file

@ -1,13 +1,13 @@
# Working with Async
Not all apps you'll build can be self-contained with synchronous code. You'll often need to interact with file systems, network interfaces, hardware, or timers.
Not all apps you'll build can be self-contained with synchronous code. You'll often need to interact with file systems, network interfaces, hardware, or timers.
So far, we've only talked about building apps with synchronous code, so this chapter will focus integrating asynchronous code into your app.
## The Runtime
By default, Dioxus-Desktop ships with the `Tokio` runtime and automatically sets everything up for you.
By default, Dioxus-Desktop ships with the `Tokio` runtime and automatically sets everything up for you.

View file

@ -9,7 +9,7 @@ In this chapter, you'll learn about:
## The use case
Let's say you're building a user interface and want to make some part of it clickable to another website. You would normally start with the HTML `<a>` tag, like so:
Let's say you're building a user interface and want to make some part of it a clickable link to another website. You would normally start with the HTML `<a>` tag, like so:
```rust
rsx!(
@ -98,7 +98,7 @@ struct ClickableProps<'a> {
children: Element<'a>
}
fn clickable(cx: Scope<ClickableProps>) -> Element {
fn Clickable(cx: Scope<ClickableProps>) -> Element {
cx.render(rsx!(
a {
href: "{cx.props.href}",
@ -162,7 +162,7 @@ struct ClickableProps<'a> {
fn clickable(cx: Scope<ClickableProps>) -> Element {
cx.render(rsx!(
a {
a {
..cx.props.attributes,
"Any link, anywhere"
}
@ -186,7 +186,7 @@ struct ClickableProps<'a> {
fn clickable(cx: Scope<ClickableProps>) -> Element {
cx.render(rsx!(
a {
a {
onclick: move |evt| cx.props.onclick.call(evt)
}
))

View file

@ -3,8 +3,8 @@
In the previous chapter, we learned about Elements and how they can be composed to create a basic User Interface. In this chapter, we'll learn how to group Elements together to form Components.
In this chapter, we'll learn:
- What makes a Component
- How to model a component and its properties in Dioxus
- What makes a Component
- How to model a component and its properties in Dioxus
- How to "think declaratively"
## What is a component?
@ -39,7 +39,7 @@ struct PostData {
}
```
If we look at the layout of the component, we notice quite a few buttons and functionality:
If we look at the layout of the component, we notice quite a few buttons and pieces of functionality:
- Upvote/Downvote
- View comments
@ -51,9 +51,9 @@ If we look at the layout of the component, we notice quite a few buttons and fun
- Crosspost
- Filter by site
- View article
- Visit user
- Visit user
If we included all this functionality in one `rsx!` call, it would be huge! Instead, let's break the post down into some core pieces:
If we included all this functionality in one `rsx!` call it would be huge! Instead, let's break the post down into some core pieces:
![Post as Component](../images/reddit_post_components.png)
@ -112,7 +112,7 @@ Let's take a look at the `VoteButton` component. For now, we won't include any i
Most of your Components will look exactly like this: a Props struct and a render function. Every component must take a `Scope` generic over some `Props` and return an `Element`.
As covered before, we'll build our User Interface with the `rsx!` macro and HTML tags. However, with components, we must actually "render" our HTML markup. Calling `cx.render` converts our "lazy" `rsx!` structure into an `Element`.
As covered before, we'll build our User Interface with the `rsx!` macro and HTML tags. However, with components, we must actually "render" our HTML markup. Calling `cx.render` converts our "lazy" `rsx!` structure into an `Element`.
```rust
#[derive(PartialEq, Props)]
@ -133,9 +133,9 @@ fn VoteButton(cx: Scope<VoteButtonProps>) -> Element {
## Borrowing
You can avoid clones using borrowed component syntax. For example, let's say we passed the `TitleCard` title as an `&str` instead of `String`. In JavaScript, the string would be copied by reference - none of the contents would be copied, but rather the reference to the string's contents are copied. In Rust, this would be similar to calling `clone` on `Rc<str>`.
You can avoid clones by using borrowed component syntax. For example, let's say we passed the `TitleCard` title as an `&str` instead of `String`. In JavaScript, the string would be copied by reference - none of the contents would be copied, but rather the reference to the string's contents are copied. In Rust, this would be similar to calling `clone` on `Rc<str>`.
Because we're working in Rust, we can choose to either use `Rc<str>`, clone `Title` on every re-render of `Post`, or simply borrow it. In most cases, you'll just want to let `Title` be cloned.
Because we're working in Rust, we can choose to either use `Rc<str>`, clone `Title` on every re-render of `Post`, or simply borrow it. In most cases, you'll just want to let `Title` be cloned.
To enable borrowed values for your component, we need to add a lifetime to let the Rust compiler know that the output `Element` borrows from the component's props.
@ -149,7 +149,7 @@ fn TitleCard<'a>(cx: Scope<'a, TitleCardProps<'a>>) -> Element {
cx.render(rsx!{
h1 { "{cx.props.title}" }
})
}
}
```
For users of React: Dioxus knows *not* to memoize components that borrow property fields. By default, every component in Dioxus is memoized. This can be disabled by the presence of a non-`'static` borrow.
@ -174,7 +174,7 @@ fn TitleCard(cx: Scope<TitleCardProps>) -> Element {
cx.render(rsx!{
h1 { "{cx.props.title}" }
})
}
}
```
to:
@ -185,7 +185,7 @@ fn TitleCard(cx: Scope, title: String) -> Element {
cx.render(rsx!{
h1 { "{title}" }
})
}
}
```
Again, this macro is optional and should not be used by library authors since you have less fine-grained control over documentation and optionality.
@ -194,9 +194,9 @@ However, it's great for quickly throwing together an app without dealing with *a
## The `Scope` object
Though very similar to React, Dioxus is different in a few ways. Most notably, React components will not have a `Scope` parameter in the component declaration.
Though very similar to React, Dioxus is different in a few ways. Most notably, React components will not have a `Scope` parameter in the component declaration.
Have you ever wondered how the `useState()` call works in React without a `this` object to actually store the state?
Have you ever wondered how the `useState()` call works in React without a `this` object to actually store the state?
React uses global variables to store this information. Global mutable variables must be carefully managed and are broadly discouraged in Rust programs.

View file

@ -27,7 +27,7 @@ Now that we have a "logged_in" flag accessible in our props, we can render two d
```rust
fn App(cx: Scope<AppProps>) -> Element {
if props.logged_in {
if cx.props.logged_in {
cx.render(rsx!{
DashboardScreen {}
})
@ -39,7 +39,7 @@ fn App(cx: Scope<AppProps>) -> Element {
}
```
When the user is logged in, then this component will return the DashboardScreen. Else, the component will render the LoginScreen.
When the user is logged in, then this component will return the DashboardScreen. If they're not logged in, the component will render the LoginScreen.
## Using match statements

View file

@ -25,27 +25,27 @@ fn main() {
dioxus::desktop::launch(App);
}
fn App(Scope) -> Element {}
fn App(Scope) -> Element {}
#[derive(PartialEq, Props)]
struct PostProps{}
fn Post(Scope<PostProps>) -> Element {}
fn Post(Scope<PostProps>) -> Element {}
#[derive(PartialEq, Props)]
struct VoteButtonsProps {}
fn VoteButtons(Scope<VoteButtonsProps>) -> Element {}
fn VoteButtons(Scope<VoteButtonsProps>) -> Element {}
#[derive(PartialEq, Props)]
struct TitleCardProps {}
fn TitleCard(Scope<TitleCardProps>) -> Element {}
fn TitleCard(Scope<TitleCardProps>) -> Element {}
#[derive(PartialEq, Props)]
struct MetaCardProps {}
fn MetaCard(Scope<MetaCardProps>) -> Element {}
fn MetaCard(Scope<MetaCardProps>) -> Element {}
#[derive(PartialEq, Props)]
struct ActionCardProps {}
fn ActionCard(Scope<ActionCardProps>) -> Element {}
fn ActionCard(Scope<ActionCardProps>) -> Element {}
```
That's a lot of components for one file! We've successfully refactored our app into components, but we should probably start breaking it up into a file for each component.
@ -61,7 +61,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
struct ActionCardProps {}
fn ActionCard(Scope<ActionCardProps>) -> Element {}
fn ActionCard(Scope<ActionCardProps>) -> Element {}
```
We should also create a `mod.rs` file in the `post` folder so we can use it from our `main.rs`. Our `Post` component and its props will go into this file.
@ -104,10 +104,10 @@ fn App(Scope) -> Element {
original_poster: "me".to_string()
}
})
}
}
```
If you tried to build this app right now, you'll get an error message saying that `Post is private, trying changing it to public`. This is because we haven't properly exported our component! To fix this, we need to make sure both the Props and Component are declared as "public":
If you tried to build this app right now, you'll get an error message saying that `Post is private, try changing it to public`. This is because we haven't properly exported our component! To fix this, we need to make sure both the Props and Component are declared as "public":
```rust
// src/post/mod.rs
@ -116,7 +116,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct PostProps {}
pub fn Post(Scope<PostProps>) -> Element {}
pub fn Post(Scope<PostProps>) -> Element {}
```
While we're here, we also need to make sure each of our subcomponents are included as modules and exported.
@ -203,7 +203,7 @@ fn App(Scope) -> Element {
original_poster: "me".to_string()
}
})
}
}
```
@ -255,7 +255,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct VoteButtonsProps {}
pub fn VoteButtons(Scope<VoteButtonsProps>) -> Element {}
pub fn VoteButtons(Scope<VoteButtonsProps>) -> Element {}
```
```rust
@ -264,7 +264,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct TitleCardProps {}
pub fn TitleCard(Scope<TitleCardProps>) -> Element {}
pub fn TitleCard(Scope<TitleCardProps>) -> Element {}
```
```rust
@ -273,7 +273,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct MetaCardProps {}
pub fn MetaCard(Scope<MetaCardProps>) -> Element {}
pub fn MetaCard(Scope<MetaCardProps>) -> Element {}
```
```rust
@ -282,7 +282,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct ActionCardProps {}
pub fn ActionCard(Scope<ActionCardProps>) -> Element {}
pub fn ActionCard(Scope<ActionCardProps>) -> Element {}
```
## Moving forward

View file

@ -1,6 +1,6 @@
# Core Topics
In this chapter, we'll cover some core topics on how Dioxus works and how to best leverage the features to build a beautiful, reactive app.
In this chapter, we'll cover some core topics about how Dioxus works and how to best leverage the features to build a beautiful, reactive app.
At a very high level, Dioxus is simply a Rust framework for _declaring_ user interfaces and _reacting_ to changes.

View file

@ -1,6 +1,6 @@
# Conditional Lists and Keys
You will often want to display multiple similar components from a collection of data.
You will often want to display multiple similar components from a collection of data.
In this chapter, you will learn:
@ -22,9 +22,9 @@ rsx!(
)
```
Instead, we need to transform the list of data into a list of Elements.
Instead, we need to transform the list of data into a list of Elements.
For convenience, `rsx!` supports any type in curly braces that implements the `IntoVnodeList` trait. Conveniently, every iterator that returns something that can be rendered as an Element also implements `IntoVnodeList`.
For convenience, `rsx!` supports any type in curly braces that implements the `IntoVnodeList` trait. Conveniently, every iterator that returns something that can be rendered as an Element also implements `IntoVnodeList`.
As a simple example, let's render a list of names. First, start with our input data:
@ -61,7 +61,7 @@ The HTML-rendered version of this list would follow what you would expect:
### Rendering our posts with a PostList component
Let's start by modeling this problem with a component and some properties.
Let's start by modeling this problem with a component and some properties.
For this example, we're going to use the borrowed component syntax since we probably have a large list of posts that we don't want to clone every time we render the Post List.
@ -98,7 +98,7 @@ fn App(cx: Scope<PostList>) -> Element {
Rust's iterators are extremely powerful, especially when used for filtering tasks. When building user interfaces, you might want to display a list of items filtered by some arbitrary check.
As a very simple example, let's set up a filter where we only list names that begin with the letter "J".
As a very simple example, let's set up a filter where we only list names that begin with the letter "J".
Let's make our list of names:
@ -117,7 +117,7 @@ let name_list = names
Rust's iterators provide us tons of functionality and are significantly easier to work with than JavaScript's map/filter/reduce.
For keen Rustaceans: notice how we don't actually call `collect` on the name list. If we `collected` our filtered list into new Vec, then we would need to make an allocation to store these new elements. Instead, we create an entirely new _lazy_ iterator which will then be consumed by Dioxus in the `render` call.
For keen Rustaceans: notice how we don't actually call `collect` on the name list. If we `collected` our filtered list into new Vec, then we would need to make an allocation to store these new elements. Instead, we create an entirely new _lazy_ iterator which will then be consumed by Dioxus in the `render` call.
The `render` method is extraordinarily efficient, so it's best practice to let it do most of the allocations for us.

View file

@ -93,7 +93,7 @@ Alternatively, `&str` can be included directly, though it must be inside of an a
rsx!( "Hello ", [if enabled { "Jack" } else { "Bob" }] )
```
This is different from React's way of generating arbitrary markup but fits within idiomatic Rust.
This is different from React's way of generating arbitrary markup but fits within idiomatic Rust.
Typically, with Dioxus, you'll just want to compute your substrings outside of the `rsx!` call and leverage the f-string formatting:
@ -138,11 +138,11 @@ rsx!(
All element attributes must occur *before* child elements. The `rsx!` macro will throw an error if your child elements come before any of your attributes. If you don't see the error, try editing your Rust-Analyzer IDE setting to ignore macro-errors. This is a temporary workaround because Rust-Analyzer currently throws *two* errors instead of just the one we care about.
```rust
// settings.json
// settings.json
{
"rust-analyzer.diagnostics.disabled": [
"macro-error"
],
],
}
```
@ -166,7 +166,7 @@ This chapter just scratches the surface on how Elements can be defined.
We learned:
- Elements are the basic building blocks of User Interfaces
- Elements can contain other elements
- Elements can contain other elements
- Elements can either be a named container or text
- Some Elements have properties that the renderer can use to draw the UI to the screen

View file

@ -15,7 +15,7 @@ With any luck, you followed through the "Putting it All Together" mini guide and
Continuing on your journey with Dioxus, you can try a number of things:
- Build a simple TUI app
- Build a simple TUI app
- Publish your search engine app
- Deploy a WASM app to GitHub
- Design a custom hook
@ -37,7 +37,7 @@ The core team is actively working on:
- Declarative window management (via Tauri) for Desktop apps
- Portals for Dioxus Core
- Mobile support
- Mobile support
- Integration with 3D renderers
- Better async story (suspense, error handling)
- Global state management

View file

@ -1,6 +1,6 @@
# "Hello, World" desktop app
Let's put together a simple "hello world" desktop application to get acquainted with Dioxus.
Let's put together a simple "hello world" desktop application to get acquainted with Dioxus.
In this chapter, we'll cover:
@ -31,7 +31,7 @@ $ tree
We are greeted with a pre-initialized git repository, our code folder (`src`) and our project file (`Cargo.toml`).
Our `src` folder holds our code. Our `main.rs` file holds our `fn main` which will be executed when our app is ran.
Our `src` folder holds our code. Our `main.rs` file holds our `fn main` which will be executed when our app is run.
```shell
$ more src/main.rs
@ -128,13 +128,13 @@ Finally, our app. Every component in Dioxus is a function that takes in `Context
fn App(cx: Scope) -> Element {
cx.render(rsx! {
div { "Hello, world!" }
})
})
}
```
### What is this `Scope` object?
Coming from React, the `Scope` object might be confusing. In React, you'll want to store data between renders with hooks. However, hooks rely on global variables which make them difficult to integrate in multi-tenant systems like server-rendering.
Coming from React, the `Scope` object might be confusing. In React, you'll want to store data between renders with hooks. However, hooks rely on global variables which make them difficult to integrate in multi-tenant systems like server-rendering.
In Dioxus, you are given an explicit `Scope` object to control how the component renders and stores data. The `Scope` object provides a handful of useful APIs for features like suspense, rendering, and more.

View file

@ -1,5 +1,5 @@
# Hooks and Internal State
In the [Adding Interactivity](./interactivity.md) section, we briefly covered the concept of hooks and state stored internal to components.
In this section, we'll dive a bit deeper into hooks, exploring both the theory and mechanics.
@ -10,7 +10,7 @@ In this section, we'll dive a bit deeper into hooks, exploring both the theory a
Over the past several decades, computer scientists and engineers have long sought the "right way" of designing user interfaces. With each new programming language, novel features are unlocked that change the paradigm in which user interfaces are coded.
Generally, a number of patterns have emerged, each with their own strengths and tradeoffs.
Generally, a number of patterns have emerged, each with their own strengths and tradeoffs.
Broadly, there are two types of GUI structures:
@ -21,7 +21,7 @@ Typically, immediate-mode GUIs are simpler to write but can slow down as more fe
Many GUIs today are written in *Retained mode* - your code changes the data of the user interface but the renderer is responsible for actually drawing to the screen. In these cases, our GUI's state sticks around as the UI is rendered. To help accommodate retained mode GUIs, like the web browser, Dioxus provides a mechanism to keep state around.
> Note: Even though hooks are accessible, you should still prefer to one-way data flow and encapsulation. Your UI code should be as predictable as possible. Dioxus is plenty fast, even for the largest apps.
> Note: Even though hooks are accessible, you should still prefer one-way data flow and encapsulation. Your UI code should be as predictable as possible. Dioxus is plenty fast, even for the largest apps.
## Mechanics of Hooks
In order to have state stick around between renders, Dioxus provides the `hook` through the `use_hook` API. This gives us a mutable reference to data returned from the initialization function.
@ -48,7 +48,7 @@ fn example(cx: Scope) -> Element {
}
```
Mechanically, each call to `use_hook` provides us with `&mut T` for a new value.
Mechanically, each call to `use_hook` provides us with `&mut T` for a new value.
```rust
fn example(cx: Scope) -> Element {
@ -182,7 +182,7 @@ By default, we bundle a handful of hooks in the Dioxus-Hooks package. Feel free
- [use_context](https://docs.rs/dioxus_hooks/use_context) - consume state provided by `use_provide_context`
For a more in-depth guide to building new hooks, checkout out the advanced hook building guide in the reference.
## Wrapping up
In this chapter, we learned about the mechanics and intricacies of storing state inside a component.

View file

@ -10,7 +10,7 @@ Before we get too deep into the mechanics of interactivity, we should first unde
Every app you'll ever build has some sort of information that needs to be rendered to the screen. Dioxus is responsible for translating your desired user interface to what is rendered to the screen. *You* are responsible for providing the content.
The dynamic data in your user interface is called `State`.
The dynamic data in your user interface is called `State`.
When you first launch your app with `dioxus::web::launch_with_props` you'll be providing the initial state. You need to declare the initial state *before* starting the app.
@ -32,7 +32,7 @@ fn main() {
}
```
When Dioxus renders your app, it will pass an immutable reference of `PostProps` to your `Post` component. Here, you can pass the state down into children.
When Dioxus renders your app, it will pass an immutable reference to `PostProps` into your `Post` component. Here, you can pass the state down into children.
```rust
fn App(cx: Scope<PostProps>) -> Element {
@ -73,14 +73,14 @@ fn App(cx: Scope)-> Element {
url: String::from("dioxuslabs.com"),
title: String::from("Hello, world"),
original_poster: String::from("dioxus")
}
}
});
cx.render(rsx!{
Title { title: &post.title }
Score { score: &post.score }
// etc
})
})
}
```
@ -102,7 +102,7 @@ We'll dive deeper into how exactly these hooks work later.
### When do I update my state?
There are a few different approaches to choosing when to update your state. You can update your state in response to user-triggered events or asynchronously in some background task.
There are a few different approaches to choosing when to update your state. You can update your state in response to user-triggered events or asynchronously in some background task.
### Updating state in listeners
@ -120,7 +120,7 @@ fn App(cx: Scope)-> Element {
"Generate a random post"
}
Post { props: &post }
})
})
}
```
@ -162,7 +162,7 @@ Whenever you inform Dioxus that the component needs to be updated, it will "rend
![Diffing](../images/diffing.png)
In React, the specifics of when a component gets re-rendered is somewhat blurry. With Dioxus, any component can mark itself as "dirty" through a method on `Context`: `needs_update`. In addition, any component can mark any _other_ component as dirty provided it knows the other component's ID with `needs_update_any`.
In React, the specifics of when a component gets re-rendered is somewhat blurry. With Dioxus, any component can mark itself as "dirty" through a method on `Context`: `needs_update`. In addition, any component can mark any _other_ component as dirty provided it knows the other component's ID with `needs_update_any`.
With these building blocks, we can craft new hooks similar to `use_state` that let us easily tell Dioxus that new information is ready to be sent to the screen.

View file

@ -1,6 +1,6 @@
# Overview
In this chapter, we're going to get "set up" with a small desktop application.
In this chapter, we're going to get set up with a small desktop application.
We'll learn about:
- Installing the Rust programming language
@ -15,16 +15,15 @@ For platform-specific guides, check out the [Platform Specific Guides](../platfo
Dioxus requires a few main things to get up and running:
- The [Rust compiler](https://www.rust-lang.org) and associated build tooling
- An editor of your choice, ideally configured with the [Rust-Analyzer LSP plugin](https://rust-analyzer.github.io)
Dioxus integrates very well with the Rust-Analyzer IDE plugin which will provide appropriate syntax highlighting, code navigation, folding, and more.
### Installing Rust
Head over to [https://rust-lang.org](http://rust-lang.org) and install the Rust compiler.
Head over to [https://rust-lang.org](http://rust-lang.org) and install the Rust compiler.
Once installed, make sure to install wasm32-unknown-unknown as a target if you're planning on deploying your app to the web.
Once installed, make sure to install wasm32-unknown-unknown as a target if you're planning on deploying your app to the web.
```
rustup target add wasm32-unknown-unknown
@ -32,7 +31,7 @@ rustup target add wasm32-unknown-unknown
### Platform-Specific Dependencies
If you are running a modern, mainstream operating system, you should need no additional setup to build WebView-based Desktop apps. However, if you are running an older version of Windows or a flavor of linux with no default web rendering engine, you might need to install some additional dependencies.
If you are running a modern, mainstream operating system, you should need no additional setup to build WebView-based Desktop apps. However, if you are running an older version of Windows or a flavor of Linux with no default web rendering engine, you might need to install some additional dependencies.
For windows users: download the [bootstrapper for Webview2 from Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/)
@ -49,13 +48,13 @@ When distributing onto older Windows platforms or less-mainstream
### Dioxus-CLI for dev server, bundling, etc.
We also recommend installing the Dioxus CLI. The Dioxus CLI automates building and packaging for various targets and integrates with simulators, development servers, and app deployment. To install the CLI, you'll need cargo (should be automatically installed with Rust):
We also recommend installing the Dioxus CLI. The Dioxus CLI automates building and packaging for various targets and integrates with simulators, development servers, and app deployment. To install the CLI, you'll need cargo (which should be automatically installed with Rust):
```
$ cargo install dioxus-cli
```
You can update the dioxus-cli at any time with:
You can update dioxus-cli at any time with:
```
$ cargo install --force dioxus-cli

View file

@ -2,7 +2,7 @@
Every app you'll build with Dioxus will have some sort of state that needs to be maintained and updated as your users interact with it. However, managing state can be particular challenging at times, and is frequently the source of bugs in many GUI frameworks.
In this chapter, we'll cover the various ways to manage state, the appropriate terminology, various patterns, and then take an overview
In this chapter, we'll cover the various ways to manage state, the appropriate terminology, various patterns, and then take an overview
## Terminology
## Terminology

View file

@ -81,7 +81,7 @@ pub fn derive_typed_builder(input: proc_macro::TokenStream) -> proc_macro::Token
/// // Using an "ID" associated with your data is a good idea.
/// data.into_iter().map(|(k, v)| rsx!(li { key: "{k}" "{v}" }))
/// }}
///
///
/// // Matching
/// {match true {
/// true => rsx!(h1 {"Top text"}),
@ -229,18 +229,18 @@ pub fn routable_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStrea
/// #[inline_props]
/// fn app(cx: Scope, bob: String) -> Element {
/// cx.render(rsx!("hello, {bob}"))
/// }
/// }
///
/// // is equivalent to
///
/// #[derive(PartialEq, Props)]
/// struct AppProps {
/// bob: String,
/// }
/// }
///
/// fn app(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!("hello, {bob}"))
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn inline_props(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {

View file

@ -94,5 +94,5 @@ Dioxus deals with arenas, lifetimes, asynchronous tasks, custom allocators, pinn
If you don't want to use a crate that uses unsafe, then this crate is not for you.
However, we are always interested in decreasing the scope of the core VirtualDom to make it easier to review. We'd be happy to welcome PRs that can eliminate unsafe code while still upholding the numerous variants required to execute certain features.
However, we are always interested in decreasing the scope of the core VirtualDom to make it easier to review. We'd be happy to welcome PRs that can eliminate unsafe code while still upholding the numerous invariants required to execute certain features.

View file

@ -5,7 +5,7 @@ This document is mostly a brain-dump on how things work. A lot of this informati
Main topics covered here:
- Fiber, Concurrency, and Cooperative Scheduling
- Suspense
- Signals
- Signals
- Patches
- Diffing
- Const/Static structures
@ -25,7 +25,7 @@ During diffing, the "caller" closure is updated if the props are not `static. Th
Hooks are a form of state that's slightly more finicky than structs but more extensible overall. Hooks cannot be used in conditionals, but are portable enough to run on most targets.
The Dioxus hook model uses a Bump arena where user's data lives.
The Dioxus hook model uses a Bump arena where user's data lives.
Initializing hooks:
- The component is created
@ -38,7 +38,7 @@ Initializing hooks:
Running hooks:
- Each time use_hook is called, the internal hook state is fetched as &mut T
- We are guaranteed that our &mut T is not aliasing by re-generating any &mut T dependencies
- We are guaranteed that our &mut T is not aliasing by re-generating any &mut T dependencies
- The hook counter is incremented
@ -62,7 +62,7 @@ The diffing engine in Dioxus expects the RealDom
Dioxus uses patches - not imperative methods - to modify the real dom. This speeds up the diffing operation and makes diffing cancelable which is useful for cooperative scheduling. In general, the RealDom trait exists so renderers can share "Node pointers" across runtime boundaries.
There are no contractual obligations between the VirtualDOM and RealDOM. When the VirtualDOM finishes its work, it releases a Vec of Edits (patches) which the RealDOM can use to update itself.
There are no contractual obligations between the VirtualDOM and RealDOM. When the VirtualDOM finishes its work, it releases a Vec of Edits (patches) which the RealDOM can use to update itself.
@ -70,11 +70,11 @@ There are no contractual obligations between the VirtualDOM and RealDOM. When th
When an EventTrigger enters the queue and "progress" is called (an async function), Dioxus will get to work running scopes and diffing nodes. Scopes are run and nodes are diffed together. Dioxus records which scopes get diffed to track the progress of its work.
While descending through the stack frame, Dioxus will query the RealDom for "time remaining." When the time runs out, Dioxus will escape the stack frame by queuing whatever work it didn't get to, and then bubbling up out of "diff_node". Dioxus will also bubble out of "diff_node" if more important work gets queued while it was descending.
While descending through the stack frame, Dioxus will query the RealDom for "time remaining." When the time runs out, Dioxus will escape the stack frame by queuing whatever work it didn't get to, and then bubbling up out of "diff_node". Dioxus will also bubble out of "diff_node" if more important work gets queued while it was descending.
Once bubbled out of diff_node, Dioxus will request the next idle callback and await for it to become available. The return of this callback is a "Deadline" object which Dioxus queries through the RealDom.
Once bubbled out of diff_node, Dioxus will request the next idle callback and await for it to become available. The return of this callback is a "Deadline" object which Dioxus queries through the RealDom.
All of this is orchestrated to keep high priority events moving through the VirtualDOM and scheduling lower-priority work around the RealDOM's animations and periodic tasks.
All of this is orchestrated to keep high priority events moving through the VirtualDOM and scheduling lower-priority work around the RealDOM's animations and periodic tasks.
```js
// returns a "deadline" object
function idle() {
@ -83,7 +83,7 @@ function idle() {
```
## Suspense
In React, "suspense" is the ability render nodes outside of the traditional lifecycle. React will wait on a future to complete, and once the data is ready, will render those nodes. React's version of suspense is designed to make working with promises in components easier.
In React, "suspense" is the ability render nodes outside of the traditional lifecycle. React will wait on a future to complete, and once the data is ready, will render those nodes. React's version of suspense is designed to make working with promises in components easier.
In Dioxus, we have similar philosophy, but the use and details of suspense is slightly different. For starters, we don't currently allow using futures in the element structure. Technically, we can allow futures - and we do with "Signals" - but the "suspense" feature itself is meant to be self-contained within a single component. This forces you to handle all the loading states within your component, instead of outside the component, keeping things a bit more containerized.

View file

@ -18,7 +18,7 @@ impl BubbleState {
}
}
/// User Events are events that are shuttled from the renderer into the VirtualDom trhough the scheduler channel.
/// User Events are events that are shuttled from the renderer into the VirtualDom through the scheduler channel.
///
/// These events will be passed to the appropriate Element given by `mounted_dom_id` and then bubbled up through the tree
/// where each listener is checked and fired if the event name matches.

View file

@ -21,7 +21,7 @@ use std::{
/// - the `rsx!` macro
/// - the [`NodeFactory`] API
pub enum VNode<'src> {
/// Text VNodes simply bump-allocated (or static) string slices
/// Text VNodes are simply bump-allocated (or static) string slices
///
/// # Example
///
@ -399,7 +399,7 @@ impl<P> AnyProps for VComponentProps<P> {
}
// Safety:
// this will downcat the other ptr as our swallowed type!
// this will downcast the other ptr as our swallowed type!
// you *must* make this check *before* calling this method
// if your functions are not the same, then you will downcast a pointer into a different type (UB)
unsafe fn memoize(&self, other: &dyn AnyProps) -> bool {

View file

@ -70,7 +70,7 @@ impl ScopeArena {
}
/// Safety:
/// - Obtaining a mutable refernece to any Scope is unsafe
/// - Obtaining a mutable reference to any Scope is unsafe
/// - Scopes use interior mutability when sharing data into components
pub(crate) fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
unsafe { self.scopes.borrow().get(&id).map(|f| &**f) }
@ -101,7 +101,7 @@ impl ScopeArena {
let parent_scope = parent_scope.map(|f| self.get_scope_raw(f)).flatten();
/*
This scopearena aggressively reuse old scopes when possible.
This scopearena aggressively reuses old scopes when possible.
We try to minimize the new allocations for props/arenas.
However, this will probably lead to some sort of fragmentation.

View file

@ -3,7 +3,7 @@ use crate::innerlude::*;
pub struct ElementIdIterator<'a> {
vdom: &'a VirtualDom,
// Heuristcally we should never bleed into 5 completely nested fragments/components
// Heuristically we should never bleed into 5 completely nested fragments/components
// Smallvec lets us stack allocate our little stack machine so the vast majority of cases are sane
stack: smallvec::SmallVec<[(u16, &'a VNode<'a>); 5]>,
}

View file

@ -9,12 +9,12 @@ use fxhash::FxHashSet;
use indexmap::IndexSet;
use std::{collections::VecDeque, iter::FromIterator, task::Poll};
/// A virtual node s ystem that progresses user events and diffs UI trees.
/// A virtual node system that progresses user events and diffs UI trees.
///
///
/// ## Guide
///
/// Components are defined as simple functions that take [`Scope`] and return an [`Element`].
/// Components are defined as simple functions that take [`Scope`] and return an [`Element`].
///
/// ```rust, ignore
/// #[derive(Props, PartialEq)]
@ -233,7 +233,7 @@ impl VirtualDom {
/// Get the [`Scope`] for the root component.
///
/// This is useful for traversing the tree from the root for heuristics or alternsative renderers that use Dioxus
/// This is useful for traversing the tree from the root for heuristics or alternative renderers that use Dioxus
/// directly.
///
/// This method is equivalent to calling `get_scope(ScopeId(0))`
@ -618,7 +618,7 @@ impl VirtualDom {
///
/// let dom = VirtualDom::new(Base);
/// let nodes = dom.render_nodes(rsx!("div"));
/// ```
/// ```
pub fn diff_vnodes<'a>(&'a self, old: &'a VNode<'a>, new: &'a VNode<'a>) -> Mutations<'a> {
let mut machine = DiffState::new(&self.scopes);
machine.stack.push(DiffInstruction::Diff { new, old });

View file

@ -66,7 +66,7 @@ impl<'a, T: 'static> UseState<'a, T> {
})
}
pub fn wtih(&self, f: impl FnOnce(&mut T)) {
pub fn with(&self, f: impl FnOnce(&mut T)) {
let mut val = self.0.wip.borrow_mut();
if let Some(inner) = val.as_mut() {

View file

@ -42,7 +42,7 @@ The HTML namespace is defined mostly with macros. However, the expanded form wou
struct base;
impl DioxusElement for base {
const TAG_NAME: &'static str = "base";
const NAME_SPACE: Option<&'static str> = None;
const NAME_SPACE: Option<&'static str> = None;
}
impl base {
#[inline]
@ -60,7 +60,7 @@ Because attributes are defined as methods on the unit struct, they guard the att
## How to extend it:
Whenever the rsx! macro is called, it relies on a module `dioxus_elements` to be in scope. When you enable the `html` feature in dioxus, this module gets imported in the prelude. However, you can extend this with your own set of custom elements by making your own `dioxus_elements` module and re-exporting the html namespace.
Whenever the rsx! macro is called, it relies on a module `dioxus_elements` to be in scope. When you enable the `html` feature in dioxus, this module gets imported in the prelude. However, you can extend this with your own set of custom elements by making your own `dioxus_elements` module and re-exporting the html namespace.
```rust
mod dioxus_elements {
@ -68,13 +68,13 @@ mod dioxus_elements {
struct my_element;
impl DioxusElement for my_element {
const TAG_NAME: &'static str = "base";
const NAME_SPACE: Option<&'static str> = None;
const NAME_SPACE: Option<&'static str> = None;
}
}
```
## Limitations:
-
-
## How to work around it:
If an attribute in Dioxus is invalid (defined incorrectly) - first, make an issue - but then, you can work around it. The raw builder API is actually somewhat ergonomic to work with, and the NodeFactory type exposes a bunch of methods to make any type of tree - even invalid ones! So obviously, be careful, but there's basically anything you can do.
@ -87,19 +87,19 @@ cx.render(rsx!{
{LazyNodes::new(move |f| {
f.raw_element(
// tag name
"custom_element",
"custom_element",
// attributes
&[f.attr("billy", format_args!("goat"))],
&[f.attr("billy", format_args!("goat"))],
// listeners
&[f.listener(onclick(move |_| {}))],
&[f.listener(onclick(move |_| {}))],
// children
&[cx.render(rsx!(div {} ))],
&[cx.render(rsx!(div {} ))],
// key
None
None
)
})}
}

View file

@ -20,7 +20,7 @@ async fn main() -> tide::Result<()> {
}
```
Dioxus LiveView runs your Dioxus apps on the server
Dioxus LiveView runs your Dioxus apps on the server
@ -36,7 +36,7 @@ async fn main() {
async fn order_shoes(mut req: WebsocketRequest) -> Response {
let stream = req.upgrade();
dioxus::liveview::launch(App, stream).await;
dioxus::liveview::launch(App, stream).await;
}
fn App(cx: Scope) -> Element {

View file

@ -21,7 +21,7 @@ $ cargo install --git https://github.com/BrainiumLLC/cargo-mobile
And then initialize your app for the right platform. Use the `winit` template for now. Right now, there's no "Dioxus" template in cargo-mobile.
```shell
$ cargo mobile init
$ cargo mobile init
```
We're going to completely clear out the `dependencies` it generates for us, swapping out `winit` with `dioxus-mobile`.

View file

@ -16,7 +16,7 @@ fn app() {
Then, in your route, you can choose to parse the Route any way you want through `use_route`.
```rust
let id: usize = use_route(&cx).path("id")?;
let id: usize = use_route(&cx).segment("id")?;
let state: CustomState = use_route(&cx).parse()?;
```

View file

@ -11,7 +11,7 @@ pub struct LinkProps<'a> {
/// The url that gets pushed to the history stack
///
/// You can either put it your own inline method or just autoderive the route using `derive(Routable)`
/// You can either put in your own inline method or just autoderive the route using `derive(Routable)`
///
/// ```rust, ignore
///

View file

@ -52,7 +52,7 @@ let content = dioxus::ssr::render_vdom(&dom);
```
## Configuring output
It's possible to configure the output of the generated HTML.
It's possible to configure the output of the generated HTML.
```rust, ignore
let content = dioxus::ssr::render_vdom(&dom, |config| config.pretty(true).prerender(true));
@ -82,7 +82,7 @@ buf.write_fmt!(format_args!("{}", args));
## Usage in pre-rendering
## Usage in pre-rendering
This crate is particularly useful in pre-generating pages server-side and then selectively loading dioxus client-side to pick up the reactive elements.

View file

@ -7,7 +7,7 @@
//!
//! # Resources
//!
//! This overview is provides a brief introduction to Dioxus. For a more in-depth guide, make sure to check out:
//! This overview provides a brief introduction to Dioxus. For a more in-depth guide, make sure to check out:
//! - [Getting Started](https://dioxuslabs.com/getting-started)
//! - [Book](https://dioxuslabs.com/book)
//! - [Reference](https://dioxuslabs.com/reference)
@ -53,7 +53,7 @@
//!
//! ## Elements & your first component
//!
//! To assemble UI trees with Diouxs, you need to use the `render` function on
//! To assemble UI trees with Dioxus, you need to use the `render` function on
//! something called `LazyNodes`. To produce `LazyNodes`, you can use the `rsx!`
//! macro or the NodeFactory API. For the most part, you want to use the `rsx!`
//! macro.
@ -74,7 +74,7 @@
//! )
//! ```
//!
//! The rsx macro accepts attributes in "struct form" and then will parse the rest
//! The `rsx!` macro accepts attributes in "struct form" and will parse the rest
//! of the body as child elements and rust expressions. Any rust expression that
//! implements `IntoIterator<Item = impl IntoVNode>` will be parsed as a child.
//!
@ -87,7 +87,7 @@
//!
//! ```
//!
//! Used within components, the rsx! macro must be rendered into an `Element` with
//! Used within components, the `rsx!` macro must be rendered into an `Element` with
//! the `render` function on Scope.
//!
//! If we want to omit the boilerplate of `cx.render`, we can simply pass in
@ -104,7 +104,7 @@
//! }
//! ```
//!
//! Putting everything together, we can write a simple component that a list of
//! Putting everything together, we can write a simple component that renders a list of
//! elements:
//!
//! ```rust, ignore
@ -146,8 +146,8 @@
//! }
//! ```
//!
//! Our `Header` component takes in a `title` and a `color` property, which we
//! delcare on an explicit `HeaderProps` struct.
//! Our `Header` component takes a `title` and a `color` property, which we
//! declare on an explicit `HeaderProps` struct.
//!
//! ```rust, ignore
//! // The `Props` derive macro lets us add additional functionality to how props are interpreted.
@ -203,8 +203,8 @@
//! }
//! ```
//!
//! Components that beging with an uppercase letter may be called through
//! traditional curly-brace syntax like so:
//! Components that begin with an uppercase letter may be called with
//! the traditional (for React) curly-brace syntax like so:
//!
//! ```rust, ignore
//! rsx!(
@ -224,7 +224,7 @@
//! ## Hooks
//!
//! While components are reusable forms of UI elements, hooks are reusable forms
//! of logic. Hooks provide us a way of retrieving state from `Scope` and using
//! of logic. Hooks provide us a way of retrieving state from the `Scope` and using
//! it to render UI elements.
//!
//! By convention, all hooks are functions that should start with `use_`. We can
@ -245,7 +245,7 @@
//! - Functions with "use_" should not be called in loops or conditionals
//!
//! In a sense, hooks let us add a field of state to our component without declaring
//! an explicit struct. However, this means we need to "load" the struct in the right
//! an explicit state struct. However, this means we need to "load" the struct in the right
//! order. If that order is wrong, then the hook will pick the wrong state and panic.
//!
//! Most hooks you'll write are simply composition of other hooks:
@ -256,8 +256,8 @@
//! users.get(&id).map(|user| user.logged_in).ok_or(false)
//! }
//! ```
//!
//! To create entirely new foundational hooks, we can use the `use_hook` method on ScopeState.
//!
//! To create entirely new foundational hooks, we can use the `use_hook` method on `ScopeState`.
//!
//! ```rust, ignore
//! fn use_mut_string(cx: &ScopeState) -> &mut String {
@ -316,9 +316,9 @@
//!
//! Alternatives to Dioxus include:
//! - Yew: supports function components and web, but no SSR, borrowed data, or bump allocation. Rather slow at times.
//! - Percy: supports function components, web, ssr, but lacks in state management
//! - Percy: supports function components, web, ssr, but lacks state management
//! - Sycamore: supports function components, web, ssr, but closer to SolidJS than React
//! - MoonZoom/Seed: opionated in the Elm model (message, update) - no hooks
//! - MoonZoom/Seed: opinionated frameworks based on the Elm model (message, update) - no hooks
//!
//! We've put a lot of work into making Dioxus ergonomic and *familiar*.
//! Our target audience is TypeSrcipt developers looking to switch to Rust for the web - so we need to be comparabale to React.