Muhammad Hamza 3ad4dbe837
Format website with prettier (#2536)
* add prettier

* ci

* run prettier

* run prettier in CI

* run prettier --write

* ignore README.md

* specify googleAnalytics

* fmt

* npm run write-translations

* fmt

* ignore i18n json files

they're autogenerated and don't like being formatted

* post merge fixes & some updates

* post merge fixes
2022-04-06 22:52:15 +05:00

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)
- 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)
## 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.
:::