The Tag API
When rendering HTML or SVG elements in Slinky, you're using the Slinky Tag API, which makes it possible to represent content trees in idiomatic Scala code.
If you've used libraries like ScalaTags before, you'll find the Slinky API very familiar, as it follows the same general tree-building style as other Scala tags libraries.
Let's get started with rendering a simple HTML element!
First, we import all HTML tags from the
Now, we can render the element:
Slinky tags always take
ReactElements as children, but these element instances can created in various ways with built in implicit conversions.
1) Other tags:
h1("I am a child element!")
2) Rendering a React component:
3) A string:
4) Scala collection types containing other React Elements:
In addition to containing other children, Slinky tags can be assigned attributes that will turn into HTML or SVG attributes at runtime
For example, we can set the HTML class of an element using the
When combined with children, attributes generally come first and children follow in a separate argument list:
When using the
aria- attributes, you can pass in the suffix as a string immediately following the
-. For example, you could pass in a
data-columns attribute as:
To add event listeners to elements, you can pass in an attribute pair assigning an event to a handler function. In Slinky, the event value is based on a type from the Scala.js DOM library (this may change in the near future, see PR #53).
Scala.js even handles the process of binding functions to the appropriate scope, so there's no need to worry about where the event handler is implemented!
Slinky supports the use of the Option type to indicate where an attribute is optional. For example:
Would be rendered as:
When attaching CSS styles to an element, Slinky follows the React API of having the
js.Dynamic value. This different from other Scala tags libraries, which usually provide individual attributes for assigning style values.
Slinky supports the React special attributes
key gives a hint of matching components in an array to React and is always a string.
ref allows you to gain access to an instance of the rendered DOM element. Slinky only supports the functional ref style, where the value of
ref is a function that takes the DOM node instance.