Kotlin/JS를 이용하여 Kotlin으로 React 프로그래밍하기!

Overview

코틀린으로 리액트 프로그래밍하기!

kotlin react image

코틀린으로 리액트 프로그래밍하기 - 블로그

코틀린으로 리액트 프로그래밍을 하시기 전에
수신 객체 지정 람다프로퍼티 위임(by)에 대해서 미리 선행하시는 걸 추천드립니다.

컴포넌트 생성하기

@JsExport
class TestComponent : RComponent<RProps, RState>() {
    override fun RBuilder.render() {
        div {
            a {
                +"Hello, world!"
            }
        }
    }
}

컴포넌트를 생성하기 위해서는 RComponent를 상속받는 클래스를 만들면 됩니다.
그리고 RBuilder.render() 확장 함수를 오버라이딩하고
HTML Kotlin DSL을 이용하여 마음껏 코드를 작성하시면 됩니다.

컴포넌트 조립하기

@JsExport
class TestComponent : RComponent<RProps, RState>() {
    override fun RBuilder.render() {
        div {
            aComponent {}
        }
    }
}

@JsExport
class AComponent : RComponent<RProps, RState>() {
    override fun RBuilder.render() {
        a {
            +"My name is jaychy-yy!"
        }
    }
}

fun RBuilder.aComponent(handler: RProps.() -> Unit): ReactElement {
    return child(AComponent::class) {
        this.attrs(handler)
    }
}

리액트를 제대로 사용하기 위해서는 한 컴포넌트에서 다른 컴포넌트를 가져와 조립할 수 있어야합니다.
RBuilder.render()는 수신 객체 지정 람다로 구현되어 있기 때문에
RBuilder.aComponent()처럼 RBuilder의 함수로 확장해야 합니다.

만약 이후에 소개할 props가 필요없을 경우 다음과 같이 handler를 제거하여도 무방합니다.

fun RBuilder.aComponent(): ReactElement {
    return child(AComponent::class) {}
}

props 사용하기

external interface AComponentProps : RProps {
    var name: String
}

@JsExport
class AComponent : RComponent<AComponentProps, RState>() {
    override fun RBuilder.render() {
        a {
            +"My name is ${props.name}!"
        }
    }
}

fun RBuilder.aComponent(handler: AComponentProps.() -> Unit): ReactElement {
    return child(AComponent::class) {
        this.attrs(handler)
    }
}

props를 사용하기 위해서는 RProps를 상속 받는 external interface를 생성하면 됩니다.
내부 프로퍼티는 임의로 라이브러리에서 생성 후 초기화 되기 때문에
반드시 var로 선언해야 합니다.

이제 AComponent를 사용하는 측에서는 attrs {}을 통해 props를 전달할 수 있습니다.

@JsExport
class TestComponent : RComponent<RProps, RState>() {
    override fun RBuilder.render() {
        div {
            aComponent {
                attrs {
                    name = "jaychy-yy"
                }
                // attrs.name = "jaychy-yy" // 이렇게도 할 수 있습니다.
            }
        }
    }
}

컴포넌트의 상태 저장하기

data class AComponentState(
    val test: String,
) : RState

@JsExport
class AComponent : RComponent<AComponentProps, AComponentState>() {

    init {
        state = AComponentState("")
    }

    override fun RBuilder.render() {
        a {
            +"My name is ${props.name}!"
        }
    }
}

컴포넌트의 상태를 저장하기 위해서는 저장할 공간을 data class로 표현합니다.
사용할 땐 state.test 형식으로 사용하고
상태를 변경하기 위해서는 setState() 메소드를 사용합니다.
또한 초기상태를 init block에서 진행할 수 있습니다.

CSS 적용하기

object MyStyles : StyleSheet("MyStyles", isStatic = true) {
    val name by css {
        fontSize = 20.px
        color = rgb(0, 0, 0)
        backgroundColor = Color.white
    }
}

스타일시트를 만드는 방법은 위와 같습니다.
생긴 것은 styled-component와 비슷해서 쉽게 사용할 수 있을 것 같습니다.
또한 보통 object로 선언하여 싱글톤으로 만들어 효율적으로 사용하게 합니다.

@JsExport
class AComponent : RComponent<AComponentProps, AComponentState>() {
    init {...}
    override fun RBuilder.render() {
        styledA {
            css {
                +MyStyles.name
            }
            +"My name is ${props.name}!"
        }
    }
}

스타일을 적용하기 위해서는 태그를 styled... 태그로 변경하여야 합니다.
styled... 태그 안에는 css() 함수를 사용할 수 있도록 CSSBuilder가 생성됩니다.

+로 연결되는 것은 내부적으로 연산자 오버로딩이 되어 있기 때문입니다.

Library & Framework

  • kotlin/js - 1.5.10
  • kotlin react - 17.0.1-pre.148-kotlin-1.4.30
  • kotlin react dom - 17.0.1-pre.148-kotlin-1.4.30
  • kotlin styled - 5.2.1-pre.148-kotlin-1.4.30

ToDoList Structure

src
  ㄴ main
      ㄴ kotlin
          ㄴ MainStyles.kt        ] - Styled Component 형식으로 정리한 스타일 객체
          ㄴ ToDoListStyles.kt    ]
          ㄴ client.kt            - 이후에 나오는 컴포넌트들을 root 아래에 두기 위한 기초 컴포넌트
          ㄴ main.kt              - ToDoList의 메인 화면 컴포넌트
          ㄴ toDo.kt              - ToDoList 내부의 ToDo를 담당하는 컴포넌트
          ㄴ toDoInsertion.kt     - ToDo를 생성하기 위한 input 컴포넌트
          ㄴ toDoList.kt          - ToDoList의 몸체 
      ㄴ resources
          ㄴ index.html           - 빌드 후 생성된 kotlin-react.learn.js 스크립트를 실행할 기초 HTML
You might also like...
A framework for building native applications using React

React Native Learn once, write anywhere: Build mobile apps with React. Getting Started · Learn the Basics · Showcase · Contribute · Community · Suppor

NativeScript empowers you to access native platform APIs from JavaScript directly. Angular, Capacitor, Ionic, React, Svelte, Vue and you name it compatible.
NativeScript empowers you to access native platform APIs from JavaScript directly. Angular, Capacitor, Ionic, React, Svelte, Vue and you name it compatible.

NativeScript empowers you to access native APIs from JavaScript directly. The framework currently provides iOS and Android runtimes for rich mobile de

Wrapper for Kustomer SDK v2.0 for react native
Wrapper for Kustomer SDK v2.0 for react native

This is a wrapper for Kustomer v2 Sdk for react native. This implements the kust

🚀 React Native Segmented Control, Pure Javascript for iOS and Android
🚀 React Native Segmented Control, Pure Javascript for iOS and Android

Installation Add the dependency: npm i react-native-segmented-control-2 Peer Dependencies Zero Dependency 🥳 Usage Import import SegmentedControl from

Library to read incoming SMS in Android for Expo (React Native)

react-native-expo-read-sms Maintainers maniac-tech Active maintainer Installation Install this in your managed Expo project by running this command: $

React Native Stone SDK Implementation (Support for both Mobile and POS versions)

react-native-stone-pos Stone Android POS Native Module Installation Stone has a private packageCloud repository, so we need to have your token before

An Animated Scrolling View for React Native applications, supported on both iOS and Android

react-native-focused-scroll An Animated Scrolling View for React Native applications, supported on both iOS and Android Preview react-native-focus-scr

 A music picker library for React Native. Provides access to the system's UI for selecting songs from the phone's music library.
A music picker library for React Native. Provides access to the system's UI for selecting songs from the phone's music library.

Expo Music Picker A music picker library for React Native. Provides access to the system's UI for selecting songs from the phone's music library. Supp

Matomo wrapper for React-Native. Supports Android and iOS. Fixed issues for native platforms build that are present in the official package.

@mccsoft/react-native-matomo Matomo wrapper for React-Native. Supports Android and iOS. Fixed issues for native platforms build that are present in th

Owner
Learning Store
Where you organize your personal learning.
Learning Store
React-native-user-interface - Change React Native userinterface at runtime

react-native-user-interface change RN userinterface at runtime. Installation npm

Ahmed Eid 0 Jan 11, 2022
This is my first Spring Boot with Kotlin project and used React as frontend.

༒☬༒ ꜱᴘʀɪɴɢ ʙᴏᴏᴛ + ᴋᴏᴛʟɪɴ ༒☬༒ This project is simple course enrolment site built with React with Typescript and Spring boot with Kotlin. Frontend - Ove

Panduka Nandara 1 Mar 22, 2022
Initiate immediate phone call for React Native on iOS and Android.

react-native-immediate-call-library Initiate immediate phone call for React Native on iOS and Android. Getting started Using npm: npm install react-na

null 7 Sep 7, 2022
Simple library to decompress files .zip, .rar, .cbz, .cbr in React Native.

Uncompress React Native Simple library to decompress files .zip, .rar, .cbz and .cbr in React Native. Installation yarn add uncompress-react-native o

Adriano Souza Costa 40 Nov 24, 2022
A react native interface for integrating payments using PayPal

react-native-paypal Getting started Installation npm install react-native-paypal Android Specific Add this to your build.gradle maven { url "https:

eKreative 14 Sep 25, 2022
Practising React by building Netflix Clone

Netflix-Clone-React Practising React by building Netflix Clone Requirements TMDB api key : Add TMDB API key to AppApi.kt Learning Resourcce Build Netf

Chetan Gupta 61 Nov 13, 2022
A 2020s compatible React Native keyboard avoiding view for Android and iOS that just works.

react-native-keyboard-shift Example Snack coming soon Until then: Clone this repo: git clone https://github.com/FullStackCraft/react-native-keyboard-s

Full Stack Craft 66 Aug 16, 2022
Make SIP calls from react-native using Linphone SDK

react-native-sip Make SIP calls from react-native using Linphone SDK Installation npm install react-native-sip Usage import { multiply } from "react-n

Woonivers 2 Jun 30, 2022
A demo for Android font typeface support in React Native!

A Step-by-step Guide to a Consistent Multi-Platform Font Typeface Experience in React Native Goal Be able to use font typeface modifiers such as fontW

Jules Sam. Randolph 53 Dec 23, 2022
Implementation of useful hooks inspired by React for Compose

useCompose React inspired hooks for Compose Installation Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the

Pavitra Golchha 20 Nov 14, 2022