Reagent is a minimalist Clojure wrapper for React. It exposes all React APIs including hooks and is one of the most popular Clojure projects. This chapter is a theoretical introduction to Reagent. We'll learn about components, third-party integrations and local state.
Reagent is a minimalist Clojure wrapper for React. It exposes all React APIs including hooks and is one of the most popular Clojure projects. This chapter is a theoretical introduction to Reagent. The code in this chapter doesn't apply directly to the Tinycanva project.
Reagent uses Hiccup to define React components. Components are vectors where the first element is the element to render, the second is the props map and the third is the child tree:
Unlike React, we can use
class instead of
className. Also these are just plain vectors, so everything we have learned about data manipulation will work:
The examples above are vanilla Clojure functions. Reagent converts these function into React Components and renders them. To test the
heading function out, we can move its definition to
app.core namespace and then use
[heading "hi" :h1] instead of
[hello] as an argument to
r/render function. As soon as you save the file, the watcher will hot-reload the code in the browser.
You can also use
reagent.core/create-element function instead of Hiccup:
This might be helpful in advanced use cases, like animations.
Native DOM elements are rendered using keywords (like
:span). Custom components can be rendered using symbols. If we want to use the
heading component defined above, we can use
heading as the first element of the vector:
There are two kinds of reaction people have after reading the above code:
"Yeah that's simple, Hiccup is easy!"
"Wait! What? How? Why square brackets for custom components?"
heading is a plain Clojure function, we should invoke it using parenthesis:
(hello name :h1), but we used square brackets instead. You can use round brackets too, but it's advisable to stick to vectors until you understand what's happening under the hood.
Reagent transforms Hiccup forms into React components using
If parenthesis is used instead of square brackets, the
heading function will be called and its output will be placed in the
card component - ie the
heading component will lose its identity as a React component. It will also lose the properties of a React component, like the ability to be memoized or the ability to have a local state.
If square brackets are used, the
heading function will not be called. Instead, Reagent will package it into a React component and place it inside
card, preserving the properties of a React component.