DEV Community

Cover image for Reagent 101 / Hiccup vs. JSX
icncsx
icncsx

Posted on

Reagent 101 / Hiccup vs. JSX

Hiccup is a Clojure library that enables us to represent HTML using Clojure vectors. In HTML and JSX, you have tags <>. In Clojure, you have vectors [].

Herein, I will lay them side by side, to show how Hiccup coupled with Reagent (a Clojure interface for React) can emulate common patterns found in React.

fragment

;; Hiccup [:<> [:p "Hello"] [:p "Bonjour"]] 
Enter fullscreen mode Exit fullscreen mode
// JSX <> <p>Hello</p> <p>Bonjour</p> </> 
Enter fullscreen mode Exit fullscreen mode

if-else rendering

;; Hiccup (defn home [{:keys [authenticated?]}] [:div.page (if authenticated? [profile] [signin])]) 
Enter fullscreen mode Exit fullscreen mode
// JSX const Home = ({isAuthenticated}) => { return ( <div className="page"> {isAuthenticated ? <Profile /> : <Signin />} </div> ); } 
Enter fullscreen mode Exit fullscreen mode

if rendering

;; Hiccup (defn foo [{:keys [child?]}] [:div "Parent" (when child? [:div "Child"])]) 
Enter fullscreen mode Exit fullscreen mode
// JSX const Foo = ({ child }) => { return ( <div> Parent {child && <div>Child</div>} </div> ); }; 
Enter fullscreen mode Exit fullscreen mode

conditional styling

;; Hiccup (defn button [{:keys [active?]}] [:button {:class [(when active? "a-class")]}]) 
Enter fullscreen mode Exit fullscreen mode
// JSX const Button = ({active}) => { return <button className={active ? 'a-class' : null} } 
Enter fullscreen mode Exit fullscreen mode

So what do you think? Not exactly a 1-1 mapping, but it's pretty similar, right? If you have some React experience under your belt, and you want to try out Reagent, I totally recommend it. You won't have a hard time, and this is partially owing to Hiccup's readability and expressiveness.

Warmly,
DH

Top comments (0)