React in Kotlin

React has become a well-established framework to build modular applications. Most often this refers to web applications written in JavaScript or TypeScript. As of this year, I’ve been tasked to write some React components in Kotlin. Without prior knowledge of Kotlin there’s a lot that I’ve learned. This post shall help me and others TypeScript developers to use their existing React expertise with the Kotlin language.

React for Kotlin has changed a bit over the past years. Similarly to how React started with components using classes, there have been changes to the syntax in Kotlin. The following Kotlin examples are functional components using React Hooks. They have been written for Kotlin 1.9.21 and React 18.2.0.

The most basic component

Let’s just return some HTML to get started. In TypeScript, I’m going to use the tsx file ending. Other than ts, tsx implies the presence of React’s HTML-like syntax.

import React from 'react';

export function HelloWorld(): React.JSX.Element {
    return <h1>Hello world!</h1>;
}
import react.FC
import react.dom.html.ReactHTML

val HelloWorld = FC("HelloWorld") {
    ReactHTML.h1 {
        +"Hello World!"
    }
}

Next, we’re going to import an existing component. This example uses the Typography component from the Material UI framework MUI.

import React from 'react';
import { Typography } from '@mui/material';

export function OpeningHoursNotice(): React.JSX.Element {
    return (
        <Typography
            component="div"
            variant="h6"
            sx={{
                flexGrow: 1,
                overflowX: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
            }}
        >The library closes at 10 PM.</Typography>
    );
}
import mui.material.Typography
import mui.material.styles.TypographyVariant
import mui.system.sx
import react.FC
import react.dom.html.ReactHTML
import web.cssom.Overflow
import web.cssom.TextOverflow
import web.cssom.WhiteSpace
import web.cssom.number

val OpeningHoursNotice = FC("OpeningHoursNotice") {
    Typography {
        component = ReactHTML.div
        variant = TypographyVariant.h6
        sx {
            flexGrow = number(1.0)
            overflow = Overflow.hidden
            textOverflow = TextOverflow.ellipsis
            whiteSpace = WhiteSpace.nowrap
        }
        +"The library closes at 10 PM."
    }
}

Props

Most React applications will use Props to hand values from parents to children. Props may be values, styles and function handlers. Let’s start with a simple, structured object.

import React from 'react';

export type Book = {
    id: number;
    title: string;
    author: string;
};

type BookItemProps = {
    book: Book;
};

export function BookItem(props: BookItemProps): React.JSX.Element {
    return (
        <li>{props.book.author} - {props.book.title}</li>
    );
}
import react.FC
import react.Props
import react.dom.html.ReactHTML

data class Book(
    val id: Int,
    val title: String,
    val author: String
)

external interface BookItemProps : Props {
    var book: Book
}

val BookItem = FC<BookItemProps>("BookItem") { props ->
    ReactHTML.li {
        +props.book.author
        +" - "
        +props.book.title
    }
}

The following example is a component which can receive props of various types.

This example still needs to be written. Come back at a later time.

Children props

This section still needs to be written. Come back at a later time.

Lists

Quite often, applications will need to display a list of information. Let’s have a look at how to render lists from common data structures.

Array

The most straight-forward data type for a list is an Array. We use the previously defined BookItem component to render the individual items.

import React from 'react';
import { Book, BookItem } from './BookItem';

const recentReads: Book[] = [
    {
        id: 1,
        title: 'Show Your Work!',
        author: 'Austin Kleon',
    },
    {
        id: 2,
        title: 'How to Be Everything',
        author: 'Emilie Wapnick',
    },
];

export function RecentReadsArray(): React.JSX.Element {
    return (
        <aside>
            <h2>Recent Reads</h2>
            <ol>
                {recentReads.map(recentRead => (
                    <BookItem
                        key={recentRead.id}
                        book={recentRead}
                    />
                ))}
            </ol>
        </aside>
    );
}
import react.FC
import react.dom.html.ReactHTML

private val recentReads = listOf(
    Book(1, "Show Your Work!", "Austin Kleon"),
    Book(2, "How to Be Everything", "Emilie Wapnick")
)

val RecentReadsArray = FC("RecentReadsArray") {
    ReactHTML.aside {
        ReactHTML.h2 {
            +"Recent Reads"
        }
        ReactHTML.ol {
            for (recentRead in recentReads) {
                BookItem {
                    key = recentRead.id.toString()
                    book = recentRead
                }
            }
        }
    }
}

Object

Sometimes we find ourselves working with lists stored in an Object. If an API provides us with an Object, this is how we render it as a list.

import React from 'react';
import { Book, BookItem } from './BookItem';

const recentReads: Record<string, Book> = {
    'fettnäpfchenführer-taiwan': {
        id: 3,
        title: 'Fettnäpfchenführer Taiwan',
        author: 'Deike Lautenschläger',
    },
};

export function RecentReadsObject(): React.JSX.Element {
    return (
        <aside>
            <h2>Recent Reads</h2>
            <ol>
                {[...Object.entries(recentReads)].map(([key, book]) => (
                    <BookItem
                        key={key}
                        book={book}
                    />
                ))}
            </ol>
        </aside>
    );
}
import react.FC
import react.dom.html.ReactHTML

private val recentReads: Map<String, Book> = mapOf(
    "fettnäpfchenführer-taiwan" to Book(4, "Fettnäpfchenführer Taiwan", "Deike Lautenschläger")
)

val RecentReadsObject = FC("RecentReadsObject") {
    ReactHTML.aside {
        ReactHTML.h2 {
            +"Recent Reads"
        }
        ReactHTML.ol {
            for ((bookId, recentRead) in recentReads) {
                BookItem {
                    key = bookId.toString()
                    book = recentRead
                }
            }
        }
    }
}

Map

Whenever untrusted user input needs to be used as a key of an Object, we should use Map instead. This prevents vulnerabilities and errors if a key is named “proto”. With security in mind, let’s dihave a look at the previous code solved with a Map.

Kotlin doesn’t seem to have the distinction between JavaScript’s Object and Map, so this example uses the Map type again.

import React from 'react';
import { Book, BookItem } from './BookItem';

const recentReads: Map<number, Book> = new Map([
    [4, {
        id: 4,
        title: 'Der letzte Außenposten',
        author: 'Anne Polifka',
    }],
]);

export function RecentReadsMap(): React.JSX.Element {
    return (
        <aside>
            <h2>Recent Reads</h2>
            <ol>
                {[...recentReads.entries()].map(([key, book]) => (
                    <BookItem
                        key={key}
                        book={book}
                    />
                ))}
            </ol>
        </aside>
    );
}
import react.FC
import react.dom.html.ReactHTML

private val recentReads: Map<Int, Book> = mapOf(
    4 to Book(4, "Der letzte Außenposten", "Anne Polifka")
)

val RecentReadsMap = FC("RecentReadsMap") {
    ReactHTML.aside {
        ReactHTML.h2 {
            +"Recent Reads"
        }
        ReactHTML.ol {
            for ((bookId, recentRead) in recentReads) {
                BookItem {
                    key = bookId.toString()
                    book = recentRead
                }
            }
        }
    }
}

Event handlers

Whenever I see React examples, they tell me how to write with a counter component. If you ever write an article about React, please don’t stop there. Also write about the difficult components. Show me how to use the various Hooks, forms, styling and other advanced methods which are needed to build a professional application! I promise that the counter is just the beginning of this chapter.

Note, we’re also adding a Fragment for the first time. Whenever you want to return multiple React nodes in one component, you can wrap them in a Fragment. Fragments are written as <Fragment></Fragment> or <></>. A Fragment won’t create a DOM node and therefore won’t affect styling while also having a better performance. It got introduced as a group of nodes because a React component can only return one node.

It’s an uncontrolled component which stores its own state using useState. For simplicity, the next example does not cache the handler function.

import React, { Fragment, useState } from 'react';

export function UnoptimizedCounter(): React.JSX.Element {
    const [count, setCount] = useState<number>(0);

    return (
        <Fragment>
            <p>The count is: {count}</p>
            <button
                type="button"
                //FIXME: Avoid expensive DOM changes with useCallback
                onClick={() => setCount(count + 1)}
            >Increase</button>
        </Fragment>
    );
}
import react.FC
import react.Fragment
import react.dom.html.ReactHTML
import react.useState
import web.html.ButtonType

val UnoptimizedCounter = FC("UnoptimizedCounter") {
    val (count, setCount) = useState(0)

    Fragment {
        ReactHTML.p {
            +"The count is: "
            +count.toString()
        }
        ReactHTML.button {
            type = ButtonType.button
            //FIXME: Avoid expensive DOM changes with useCallback
            onClick = { _: Any -> setCount(count + 1) }
            +"Increase"
        }
    }
}

Caching handlers with useCallback

Changes to the browser’s DOM are relatively expensive. To improve the performance of a component, we can choose to cache a handler function using the React Hook useCallback.

import React, { Fragment, useCallback, useState } from 'react';

export function Counter(): React.JSX.Element {
    const [count, setCount] = useState<number>(0);

    const handleIncrease = useCallback(() => {
        // This uses the callback variant of setState.
        setCount(value => value + 1);
    }, []);

    return (
        <Fragment>
            <p>The count is: {count}</p>
            <button
                type="button"
                onClick={handleIncrease}
            >Increase</button>
        </Fragment>
    );
}
import react.FC
import react.Fragment
import react.dom.events.MouseEvent
import react.dom.html.ReactHTML
import react.useCallback
import react.useState
import web.html.ButtonType
import web.html.HTMLButtonElement

val Counter = FC("Counter") {
    val (count, setCount) = useState(0)

    val handleIncrease = useCallback<(it: MouseEvent<HTMLButtonElement, *>) -> Unit> {
        setCount { value -> value + 1 }
    }

    Fragment {
        ReactHTML.p {
            +"The count is: "
            +count.toString()
        }
        ReactHTML.button {
            type = ButtonType.button
            onClick = handleIncrease
            +"Increase"
        }
    }
}

Form events

Let’s build a small form. For the best accessibility, let’s listen to the submit event on the form instead of click on the submit button. Did you know, you can submit a form by pressing Ctrl + Enter while any input is focused?

Note, the HTML button has the default type submit. Clicking it will emit a submit event on the surrounding form node. For clarity I explicitly set the type. Many UI frameworks for React define a Button component with the default type button. If you change the code to use your Button component, you don’t have to worry which type is being used.

import React, { useCallback, useState } from 'react';
import { sendBookOrder } from '../api.ts';

export function BookOrderForm(): React.JSX.Element {
    const [ title, setTitle ] = useState<string>('');

    //FIXME: Avoid expensive DOM changes by reading the input values from the event
    const handleSubmit: React.FormEventHandler<HTMLFormElement> = useCallback(event => {
        // We don't want the browser to handle this and possibly reload the page.
        event.preventDefault();

        sendBookOrder(title);
    }, [title]);

    const handleTitleChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
        event => setTitle(event.target.value),
        []
    );

    return (
        <form
            onSubmit={handleSubmit}
        >
            <h2>Order Service</h2>
            <label>
                Book title:
                <input
                    value={title}
                    onChange={handleTitleChange}
                />
            </label>
            <button type="submit">Order</button>
        </form>
    );
}
import react.FC
import react.dom.events.ChangeEventHandler
import react.dom.events.FormEventHandler
import react.dom.html.ReactHTML
import react.useCallback
import react.useState
import sendBookOrder
import web.html.ButtonType
import web.html.HTMLFormElement
import web.html.HTMLInputElement

val BookOrderForm = FC("BookOrderForm") { props ->
    val (title, setTitle) = useState("")

    val handleSubmit = useCallback<FormEventHandler<HTMLFormElement>> { event ->
        event.preventDefault()

        sendBookOrder(title)
    }

    val handleTitleChange = useCallback<ChangeEventHandler<HTMLInputElement>> { event ->
        setTitle(event.target.value)
    }

    ReactHTML.form {
        onSubmit = handleSubmit
        ReactHTML.h2 {
            +"Order Service"
        }
        ReactHTML.label {
            +"Book title:"
            ReactHTML.input {
                value = title
                onChange = handleTitleChange
            }
        }
        ReactHTML.button {
            type = ButtonType.submit
            +"Order"
        }
    }
}

Select input

A select is a dropdown which allows only one option to be selected.

import React, { useCallback, useState } from 'react';

export function LibrarySelect(): React.JSX.Element {
    const [library, setLibrary] = useState<string>('ksml-main');

    const handleChange: React.ChangeEventHandler<HTMLSelectElement> = useCallback(event => {
        setLibrary(event.target.value);
    }, []);

    return (
        <label>
            Library:
            <select
                value={library}
                onChange={handleChange}
            >
                <optgroup label="Kaohsiung">
                    <option value="ksml-main">KSML Main Branch</option>
                    <option value="ksml-gushan">KSML Gushan Branch</option>
                </optgroup>
                <optgroup label="Vancouver">
                    <option value="vpl-central">VPL Central Library</option>
                    <option value="vpl-hastings">VPL Hastings Branch</option>
                </optgroup>
            </select>
        </label>
    );
}
import react.FC
import react.Fragment
import react.dom.events.ChangeEventHandler
import react.dom.html.ReactHTML
import react.useCallback
import react.useState
import web.html.HTMLSelectElement

val LibrarySelect = FC("LibrarySelect") {
    val (library, setLibrary) = useState("ksml-main")

    val handleChange: ChangeEventHandler<HTMLSelectElement> = useCallback { event ->
        setLibrary(event.target.value)
    }

    Fragment {
        ReactHTML.label {
            +"Library:"
            ReactHTML.select {
                value = library
                onChange = handleChange
                ReactHTML.optgroup {
                    label = "Kaohsiung"
                    ReactHTML.option {
                        value = "ksml-main"
                        +"KSML Main Branch"
                    }
                    ReactHTML.option {
                        value = "ksml-gushan"
                        +"KSML Gushan Branch"
                    }
                }
                ReactHTML.optgroup {
                    label = "Vancouver"
                    ReactHTML.option {
                        value = "vpl-central"
                        +"VPL Central Library"
                    }
                    ReactHTML.option {
                        value = "vpl-hastings"
                        +"VPL Hastings Branch"
                    }
                }
            }
        }
    }
}

Data attributes

Data atrributes allow us to specify custom, non-standard values on a DOM node. These are sometimes used for styling or recognising form inputs in JavaScript. Another common use case is to apply IDs to components for end-to-end testing. In the later case they will be used by a browser-based testing framework like Cypress of Selenium to find a specific component.

import React from 'react';

export function Outro(): React.JSX.Element {
    return (
        <p
            data-test-id="outro"
        >Thanks for reading!</p>
    );
}
import react.FC
import react.dom.html.ReactHTML

val Outro = FC("Outro") {
    ReactHTML.span {
        asDynamic()["test-id"] = "outro"
        +"Thanks for reading!"
    }
}

Ideas for more sections

  • Events handlers
    • textarea
    • Checkboxes and radio inputs
  • useMemo, useEffect and other Hooks
  • APIs and fetching data
  • Error Boundary
  • render props
  • Context

I never used it, but might be useful

  • Themes and Portals
  • useTransition