Playing with Kotlin React official wrapper

Ramon Rivas
2 min readNov 19, 2017

--

JetBrains creation has gained a lot in popularity, especially since Google's announcement in May '17 that Kotlin will be officially supported in Android.

I have been using Kotlin in Java projects for some time, and only recently decided to experiment with the JavaScript support. I was not familiar with React library, but decided to give it a try as this is the first library officially supported with wrappers by JetBrains.

The Kotlin React wrapper website explains the basics on how to start using the library, but if you need to learn about React, you have to follow the React documentation with code examples in JavaScript. I decided to follow the official React tutorial, and at the same time do my own implementation of the example code using Kotlin.

To simplify writing DOM elements in JavaScript, React provides an extension to JavaScript called JSX.

Square component in React with JSX

In the case of Kotlin, the wrapper defines a DSL that makes writing code as simple than with React directly.

Square component in React with Kotlin

I have implemented the React tutorial in Kotlin, with a commit for each of the steps described on the tutorial. On each commit, I've tried to follow the original code as close as possible, although in a few cases I used a Kotlin specific variant to make the code more clear.

The Kotlin code for the React tutorial can be found in my GitHub repository, here. All commits can be run with the following command:

gradlew run

The command will compile the code (if needed) and will run a server. Once the code is running, and to see the application working, open a web browser in the following address:

http://localhost:8088/

After finishing testing, the server must be stopped, which can be done with the command:

gradlew stop

The project uses Kotlin gradle frontend plugin (in development), which allows a very simple interaction with JavaScript world technologies like NPM and Webpack. The documentation of the plugin can be found here.

Conclusion

Using Kotlin for JavaScript seems to be as easy as using it for Java development. With the help of the frontend plugin, developers already using gradle for Java projects don't even need to learn and install the tooling required for modern JavaScript applications.

I hope this implementation of the tutorial helps some developers to start using Kotlin for web development.

--

--