Reagent uses a datastructure known as Hiccup to describe HTML. Hiccup describes HTML elements and user-defined components as a nested ClojureScript vector:
[:div {:class "parent"}
[:p {:id "child-one"} "I'm first child element."]
[:p "I'm the second child element."]]
As described below, reagent provides a number of extensions and conveniences to Hiccup, but the general rules of Hiccup are as follows:
(name keyword) is the tag of the HTML element.nil child nodesReagent and React ignore nil nodes, which allow conditional logic in Hiccup forms:
(defn my-div [child?]
[:div
"Parent Element"
(when child? [:div "Child element"])])
In this example (my-div false) will evaluate to [:div "Parent Element" nil], which reagent will simply treat the same as [:div "Parent Element"].
style attributeThe :style attribute can be written a string or as a map. The following two are equivalent:
[:div {:style "color: red; font-weight: bold"} "Alert"]
[:div {:style {:color "red"
:font-weight "bold"}
"Alert"]
The map form is the same as React's style attribute, except that when using the map form of the style attribute, the keys should be the same name as the CSS attribute as shown in the above example (not camel cased as is required JavaScript).
class attributeIn JavaScript, class is a reserved keyword, so React uses the className to specify class attibutes. Reagent just uses class.
As of reagent 0.8.0, the class attribute accepts a collection of classes and will remove any nil value:
[:div {:class ["a-class" (when active? "active") "b-class"]}]
Reagent extends standard Hiccup in one way: it is possible to "squeeze" elements together by using a > character.
This:
[:div
[:p
[:b "Nested Element"]]]
can be written as:
[:div>p>b "Nested Element"]
The primary entrypoint to the reagent library is reagent.core/render.
(ns example
(:require [reagent.core :as r]))
(defn render-simple []
(r/render [:div [:p "Hello world!"]]
(.-body js/document)))
This render function expects one of two things:
If it encounters a ClojureScript vector, it will interpret it as Hiccup. Reagent expects one of two things in the first position of the vector:
:div or :span, which it will create using React.createElementmy-component.If it is symbol, then reagent will evaluate a function by that name. Reagent expects one of three things from this function:
Can you improve this documentation?Edit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |