mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
* Docs overhaul part2 * fix links and require them for CI * remove translations for 0.17 * remove a bunch of unused documentation * run prettier * fixup links and locations of some translations
70 lines
1.8 KiB
Plaintext
70 lines
1.8 KiB
Plaintext
---
|
|
title: 'Function Components'
|
|
slug: /concepts/function-components
|
|
---
|
|
|
|
Lets revisit this previous statement:
|
|
|
|
> Yew mostly operates on the idea of keeping everything that a reusable piece of
|
|
> UI may need, in one place - rust files.
|
|
|
|
It is only partially correct, "rust files" should be replaced with "components".
|
|
|
|
## What are Components?
|
|
|
|
Components are the building blocks of Yew.
|
|
|
|
They:
|
|
|
|
- Take arguments in form of [Props](./properties.mdx)
|
|
- Can have their own state
|
|
- Get computed into HTML visible to the user (DOM)
|
|
|
|
## Two flavours of Yew Components
|
|
|
|
You are currently reading about function components - the recommended way to write components when starting with Yew.
|
|
|
|
But we have to note that there is a more advanced, but less recommended way to write them - [Struct components](advanced-topics/struct-components/introduction.mdx)
|
|
|
|
## Creating function components
|
|
|
|
To create a function component add the `#[function_component]` attribute to a function.
|
|
Also name the function in PascalCase as it is the convention for naming components.
|
|
|
|
```rust
|
|
use yew::{function_component, html, Html};
|
|
|
|
#[function_component]
|
|
fn HelloWorld() -> Html {
|
|
html! { "Hello world" }
|
|
}
|
|
|
|
// Then somewhere else you can use the component inside the `html!`
|
|
#[function_component]
|
|
fn App() -> Html {
|
|
html! {<HelloWorld />}
|
|
}
|
|
```
|
|
|
|
## What happens to components
|
|
|
|
Yew will build a tree of these components that from the previous example would look like this:
|
|
|
|
```md
|
|
<App />
|
|
|
|
|
<HelloWorld />
|
|
```
|
|
|
|
It will call those functions / function components to compute a virtual version of the DOM (VDOM) that you as the library user see as the `Html` type.
|
|
|
|
Yew will compare current DOM with VDOM and only update the new/changed/necessary parts.
|
|
|
|
This is what we call **rendering**.
|
|
|
|
:::note
|
|
|
|
Behind the scenes `Html` type is just an alias for `VNode` - virtual node.
|
|
|
|
:::
|