I’ve got some sugar functions that let me use kotl...
# react
r
I’ve got some sugar functions that let me use kotlin data classes as the props type for functional components, allowing for destructuring and other data class things. Is that of interest to people? I make extensive use of it in my own codebase now, and I’m guessing others have run into similar needs / interests
👍 1
c
I'd be curious to see what it looks like
r
Example of usage (reactFunction is my sugar):
Copy code
data class PinSectionProps(
    val pinList: List<Pin>,
    val scale: PinButtonScale = PinButtonScale.Small,
    val canDrag: Boolean,
    val className: String
) : RProps

val PinSection = reactFunction<PinSectionProps> { (pinList, scale, canDrag, className) ->
    styledDiv {

etc etc
Code that does it (using the RClass<P> type for various reasons I can’t remember at the moment):
Copy code
inline fun <reified P : RProps> reactFunction(crossinline function: RBuilder.(P) -> Unit): RClass<P> =
    buildReactFunction(P::class) { props ->
        buildElement { function(props) }
    }

fun <P : RProps> buildReactFunction(kClass: KClass<P>, builder: (props: P) -> ReactElement) = { props: P ->
    ensureKotlinClassProps(props, kClass.js)
        .let(builder)
}.unsafeCast<RClass<P>>()

private fun <P : RProps> ensureKotlinClassProps(props: P, jsClass: JsClass<P>): P = if (props::class.js == jsClass) {
    props
} else {
    val newProps = js("new jsClass()")
    objectAssign(newProps, props)
    newProps.unsafeCast<P>()
}
I also have a builder function that helps you add things like “key” and “children” to your props, so that’s a solved problem for me
I’m weighing the options of publishing it as a tiny library if its useful to people
j
I am a noob, but I did encounter that I couldn't pass my props as a data class to a component and after that couldn't retrieve as such, so definitely looks very helpful 🙂
👍 1
r