Attributes aren't visible in Rustdoc generated documentation. The doc strings of your properties should mention whether a prop is optional and if it has a special default value.
Properties
Properties enable child and parent components to communicate with each other. Every component has an associated properties type which describes what is passed down from the parent. In theory, this can be any type that implements the Properties trait, but in practice, there is no reason for it to be anything but a struct where each field represents a property.
Derive macro#
Instead of implementing the Properties trait yourself, you should use #[derive(Properties)] to automatically generate the implementation instead. Types for which you derive Properties must also implement PartialEq.
Field attributes#
When deriving Properties, all fields are required by default. The following attributes allow you to give your props initial values which will be used unless they are set to another value.
#[prop_or_default]#
Initialize the prop value with the default value of the field's type using the Default trait.
#[prop_or(value)]#
Use value to initialize the prop value. value can be any expression that returns the field's type. For example, to default a boolean prop to true, use the attribute #[prop_or(true)].
#[prop_or_else(function)]#
Call function to initialize the prop value. function should have the signature FnMut() -> T where T is the field type.
PartialEq#
Properties require PartialEq to be implemented. This is so that they can be compared by Yew to call the changed method only when they change.
Memory/speed overhead of using Properties#
Internally properties are reference counted. This means that only a pointer is passed down the component tree for props. It saves us from the cost of having to clone the entire props, which might be expensive.
Make use of AttrValue which is our custom type for attribute values instead of defining them as String or another similar type.
Example#
use Properties;
/// Importing the AttrValue from virtual_dom
use AttrValue;
Props macro#
The yew::props! macro allows you to build properties the same way the html! macro does it.
The macro uses the same syntax as a struct expression except that you cannot use attributes or a base expression (Foo { ..base }). The type path can either point to the props directly (path::to::Props) or the associated properties of a component (MyComp::Properties).
use ;