Elements
DOM nodes#
There are many reasons why you might want to create or manage DOM nodes manually in Yew, such as when integrating with JS libraries that can cause conflicts with managed components.
Using web-sys, you can create DOM elements and convert them into a Node - which can then be used as an Html value using VRef:
use ;
use *;
use document;
Dynamic tag names#
When building a higher-order component you might find yourself in a situation where the element's tag name is not static. For example, you might have a Title component that can render anything from h1 to h6 depending on a level prop. Instead of having to use a big match expression, Yew allows you to set the tag name dynamically using @{name} where name can be any expression that returns a string.
use *;
let level = 5;
let text = "Hello World!".to_owned;
html! ;
Boolean Attributes#
Some content attributes (e.g checked, hidden, required) are called boolean attributes. In Yew, boolean attributes need to be set to a bool value:
use *;
html! ;
This will result in HTML that is functionally equivalent to this:
This div is hidden.
Setting a boolean attribute to false is equivalent to not using the attribute at all; values from boolean expressions can be used:
use *;
let no = 1 + 1 != 2;
html! ;
This will result in the following HTML:
This div is NOT hidden.
String-like attributes#
But apart from a select few boolean attributes, you will probably be dealing with a lot of string-like HTML attributes and Yew has a few options to pass string-like values to components.
use ;
let str_placeholder = "I'm a str!";
let string_placeholder = Stringfrom;
let attrvalue_placeholder = from;
html! ;
They are all valid but we encourage you to favor Yew's custom AttrValue, especially if you need to clone or pass them as properties to another component.
Optional attributes for HTML elements#
Most HTML attributes can use optional values (Some(x) or None). This allows us to omit the attribute if the attribute is marked as optional.
use *;
let maybe_id = Some;
html! ;
If the attribute is set to None, the attribute will not be set in the DOM.
Children#
Most HTML elements accept arbitrary HTML as children, however, there is a set of them that doesn't accept any children at all. These elements are called void elements, and they are:
<area /><base /><base /><br /><col /><embed /><hr /><img /><input /><link /><meta /><param /><source /><track /><wbr /><textarea />
Attempting to provide children to these elements will result in a compilation error or, if the element tag is chosen dynamically, in a panic.
The case of <textarea>#
The <textarea> element is special; The modern HTML specification states that children of <textarea> define its default value, however in Yew it's specified differently. Instead of writing
{"default value"}
Which would fail to compile, it's customary to write