Learn how to build Functional Front-ends with ClojureScript and React.

微信扫一扫,分享到朋友圈

Learn how to build Functional Front-ends with ClojureScript and React.

Learn how to build Functional Front-ends with ClojureScript and React.

You probably heard about React, and did you hear about Reagent? Reagent is a minimalistic interface between ClojureScript and React.

ClojureScript, just as Elm, ReasonML and EcmaScript compile/transpile to JavaScript.

With Reagent you can define components using nothing else but plain ClojureScript functions and data structures .

Let’s take a look at a couple examples and see how they compare. This is not a rant on React. React is awesome! Nor a rant on JS. JS is awesome too! This is to show how React looks like in a language with immutable and persistent data structures.

A Stateless Component

The simplest component in Reagent and in React is just a function.

Very often in JavaScript you would see them as const one liners:

const HelloMessage = props => 
Hello {props.name}
;

A Stateful Component

Since Reagent is build on top of CLJS (ClojureScript) immutable data structures there is no need for extra libraries (Redux, MobX) or syntax ( this.setState ) to work with your state. In CLJS you would use atoms (reference type in CLJS) for dealing with your state.

In this example we are creating a let binding for an atom — inside our counter function. The let binding is available only inside the scope of the function and then we are swap!-ing the value with on-click by using inc (increment) function.

A Class Component with Life Cycle Methods

This example shows a class component with life cycle methods.

In Reagent we would use them less than 1%. The reason for that are — atoms — they will keep track when they should be updated. In Reagent we could write this component like this, without a need for componentDidMount :

(defn timer []
(let [seconds (r/atom 0)]
(fn []
(js/setInterval #(swap! seconds inc) 1000)
[:div
"Seconds: " @seconds])))

Want to learn more?

If you would like to learn more about ClojureScript and Reagent try this FREE video course and build GIGGIN app.

More information about the course at learnreagent.com

And if you like this article you should follow me on Medium and Twitter I only write/tweet about programming and technology.

Learn Visual Basic: Best Visual Basic tutorials & best Visual Basic books 2018

上一篇

Carpooling service Klaxit partners with Uber for last-minute changes

下一篇

你也可能喜欢

Learn how to build Functional Front-ends with ClojureScript and React.

长按储存图像,分享给朋友