Jetpack Compose is rapidly gaining traction as the modern UI toolkit for Android development. However, its capabilities extend beyond mobile apps. With Compose for Web, you can now leverage the power and flexibility of Jetpack Compose to build interactive web applications. This comprehensive guide delves into using Compose for Web within the broader Jetpack Compose ecosystem.
What is Compose for Web?
Compose for Web is a Kotlin/JS-based framework that allows you to build web applications using the same declarative UI paradigm as Jetpack Compose for Android. It leverages Kotlin’s multiplatform capabilities to provide a consistent development experience across platforms.
Why Use Compose for Web?
- Code Reuse: Share code between your Android app and web application.
- Declarative UI: Build UIs with a modern, declarative approach.
- Kotlin/JS: Uses Kotlin/JS, enabling seamless interoperability with existing JavaScript libraries.
- Component-Based Architecture: Create reusable UI components for better maintainability.
Setting Up Your Project
To start using Compose for Web, you’ll need to set up a new Kotlin/JS project with Gradle. Here’s how to get started:
Step 1: Create a New Kotlin/JS Project
You can create a new Kotlin/JS project using IntelliJ IDEA or directly from the command line. Using IntelliJ IDEA:
- Open IntelliJ IDEA and click “New Project.”
- Select “Kotlin” in the left panel.
- Choose “Kotlin/JS Application” in the main panel.
- Configure the project name, location, and build system (Gradle Kotlin DSL is recommended).
- Click “Create.”
Step 2: Add Dependencies
Open your build.gradle.kts
file and add the necessary Compose for Web dependencies:
plugins {
kotlin("js") version "1.9.20"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
dependencies {
implementation(compose.web.core)
implementation(compose.html.core)
implementation(kotlin("stdlib-js"))
testImplementation(kotlin("test-js"))
}
kotlin {
js(IR) {
browser {
commonWebpackConfig {
cssSupport {
enabled = true
}
}
testTask {
useKarma {
useChromeHeadless()
}
}
}
binaries.executable()
}
sourceSets["main"].dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-js")
}
}
Make sure you have the correct Kotlin version (1.9.20
in this example) and include the Compose repository.
Step 3: Create the Main Composable
Create a Kotlin file (e.g., Main.kt
) and define the main composable function. This is the entry point for your web application.
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.window.CanvasBasedWindow
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
fun main() {
@OptIn(ExperimentalComposeUiApi::class)
CanvasBasedWindow("Compose for Web") {
Style {
body {
backgroundColor(Color("#f0f0f0"))
margin(0.px)
display(DisplayStyle.Flex)
justifyContent(JustifyContent.Center)
alignItems(AlignItems.Center)
height(100.percent)
}
}
Div({
style {
backgroundColor(Color.White)
padding(20.px)
borderRadius(8.px)
boxShadow(0.px, 4.px, 16.px, Color.gray)
textAlign(TextAlign.Center)
}
}) {
H1({
style {
color(Color("#333"))
fontSize(32.px)
}
}) {
Text("Hello, Compose for Web!")
}
P({
style {
color(Color("#666"))
fontSize(16.px)
}
}) {
Text("Building interactive web applications with Jetpack Compose.")
}
}
}
}
This code sets up a basic HTML structure with CSS styling and displays a simple “Hello, Compose for Web!” message.
Step 4: Run the Application
To run your Compose for Web application, use the following Gradle task:
./gradlew browserRun
This command will build and launch the application in your default web browser.
Advanced Features
State Management
Managing state is crucial for building interactive web applications. You can use Compose’s built-in state management capabilities or integrate with external libraries.
import androidx.compose.runtime.*
import org.jetbrains.compose.web.dom.*
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Div {
Button({ onClick { count++ } }) {
Text("Increment")
}
Span {
Text("Count: $count")
}
}
}
This example uses mutableStateOf
and remember
to manage the state of a counter.
Event Handling
Compose for Web provides event handling capabilities to respond to user interactions.
import org.jetbrains.compose.web.dom.*
@Composable
fun TextInput() {
var text by remember { mutableStateOf("") }
Input(type = InputType.Text) {
value(text)
onInput { event ->
text = event.value
}
}
Text("You entered: $text")
}
This example captures user input from a text field and updates the displayed text.
Styling and CSS
Compose for Web supports CSS styling to customize the appearance of your application. You can use inline styles or external stylesheets.
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
@Composable
fun StyledButton(text: String) {
Button({
style {
backgroundColor(Color("#4CAF50"))
color(Color.White)
padding(10.px, 20.px)
border(0.px)
borderRadius(5.px)
cursor("pointer")
hover {
backgroundColor(Color("#3e8e41"))
}
}
}) {
Text(text)
}
}
This example defines a styled button with custom colors, padding, and hover effects.
Integrating with JavaScript
Compose for Web allows you to integrate with existing JavaScript libraries. You can use Kotlin’s external
keyword to define interfaces for JavaScript functions and objects.
import kotlin.js.*
import org.jetbrains.compose.web.dom.*
@JsModule("external-library")
@JsNonModule
external fun externalFunction(param: String): String
@Composable
fun JavaScriptIntegration() {
val result = externalFunction("Hello from Kotlin!")
Div {
Text("Result from JavaScript: $result")
}
}
This example demonstrates how to call a JavaScript function from Kotlin code.
Best Practices
- Component-Based Design: Break down your UI into reusable components.
- State Management: Use Compose’s state management capabilities or integrate with external libraries like Redux or Mobius.
- Styling: Use CSS styling to customize the appearance of your application.
- Testing: Write unit tests and integration tests to ensure the quality of your code.
Conclusion
Compose for Web opens up exciting possibilities for building web applications with the power and flexibility of Jetpack Compose. By leveraging Kotlin’s multiplatform capabilities, you can share code between your Android app and web application, creating a consistent and efficient development experience. As the framework evolves, expect even more advanced features and capabilities to be added, making Compose for Web a compelling choice for modern web development.