React Functional Components with Kotlin/JS

I’ve been playing with Kotlin/JS and React lately. I’ve been wanting to learn more about frontend development, and since I’m very familiar with Kotlin, thought Kotlin/JS and React would be a good entry point.


I’m not even going to pretend to be able to explain React. You should go read the official documentation if you want to learn more. A quick primer: React enables the creation of Components which are reuseable and composable and built from other components and standard HTML tags using a XML-like syntax called JSX. Components can be stateful and take properties as inputs. Here’s an example component right from the home page of React:

React Functional Components

More modern React uses Functional Components. These are just standard JavaScript functions which accept a parameter and return a React element. Here is the functional version of the previous component example.

Kotlin/JS and React

Using the wrappers for React provided by JetBrains, you can define React components in Kotlin/JS. Because Kotlin is a type safe language, there is a bit more boiler plate required to reproduce the original example.

Kotlin/JS and React Functional Components

Also provided by the Kotlin wrappers for React is a functional component builder. Again, because of type safety, there is some builder plate and it is both similar and different from the class version of the component.

Kotlin/JS React Compiler Plugin

I’ve got some background with Kotlin compiler plugins, so I looked at the boiler plate required to build functional components in Kotlin/JS and knew it could be better. The most optimal reduction of boiler plate might look something like the following.

How do we get this function to be a valid Kotlin/JS React functional component? Some things to notice:

  1. The parameters to the function are exactly the properties of the interface.
  2. The body of the function is exactly the lambda used for the call to .

Kotlin React Function Compiler Plugin

With the new Kotlin/JS compiler plugin kotlin-react-function for React functional components, the above function can be converted using a single annotation .

When the annotation is added to the function along with the Gradle plugin, the boiler plate required is automatically generated and the function is transformed to use the boiler plate.

Looking back at the JavaScript version of this functional component, this is very similar and reduces the boilerplate required significantly.

My Kotlin/JS and React journey is just beginning, but hopefully this compiler plugin will make creating React functional components in Kotlin/JS much easier for me and everyone else!