Integrating With React Components
React is one of the most popular JavaScript libraries for building user interfaces. It's architecture is based on encapsulated components that manage their own state. There are a lot of free React components available, you can find a list of most popular on this page.
Although KVision offers a rich set of different components, there will be occasions when you will need to use something that KVision does not offer. Fortunately both KVision and Kotlin/JS ecosystem allows you to include any NPM dependencies in your project. And KVision has full support for embedding external React components inside your application. React components are standardized, so it's fairly easy to learn how to use them.
Dependencies
To use React component just add kvision-react
module and the required NPM dependencies to your build.gradle.kts
file.
Simple components
Let's start with a simple example and react-awesome-button component. First you need to declare the type of data being passed into the component.
Having this declaration, you can use the component with the react { ... }
DSL builder function.
Advanced components
React components can be stateful and can maintain internal state data. With KVision it's possible to logically relocate this internal state from React component into KVision component, where it can be accessed from the other parts of the application.
Let's use an advanced ACE code editor with react-ace component. The basic declaration is similar to the previous example (of course the component has a lot more properties then covered by this example).
Now you can use the component with advanced form of the DSL builder functionreact(initialState) { getState, changeState -> ... }
.
You initialize the KVision React
component with some initial state, which can be any type T
you need. You use getState(): () -> T
function to retrieve the current state and assign the correct value to the React component input property. And you can use changeState(): ((T) -> T) -> Unit
function to modify the state (most of the time this function will be used with some React callbacks). After creating this two-way bindings you can both read and change the current state of the component with its .state
property.
Accessing internal API of React components
Sometimes it may be necessary to access the internal api of a React component, beyond the attributes exposed in the interface. To do this, you can use the ref
variable provided by PropsWithRef<T>
, which is part of the kotlin-react
library:
Using KVision components as React children
Most React components can have children. Typically you can easily add other React components as React children. But you may also use KVision components with a help of kv
helper function.
Resources
When using React components you will also need to include resources (like CSS). Use require
function inside some init {}
block for this purpose.
Last updated