Hi everyone, I was wondering if there was a way to...
# react
p
Hi everyone, I was wondering if there was a way to make a generic react component in Kotlin/JS. The following minimal example seems to be working:
Copy code
interface MyGenericCompProps<T> : RProps

fun <T> myGenericComp() = { props: MyGenericCompProps<T> ->
    buildElement {
        div {
            +"Generic component"
        }
    }
}

val genericCompContainer = functionalComponent<RProps> {
    child(myGenericComp<Any>())
}
But I am not sure if it's a good way to make a component. Do any of you see issues with my example ?
t
1. For generic
Copy code
external interface MyGenericProps<T>: RProps

fun <T> RBuilder.myGenericComp(props: MyProps<T>) {
     // add elements
}
p
@turansky Thanks for your answer. But as I understand it this would not create a new functional component would it ? Besides, I don't see how I could use this method to pass children in props (as it is a final property). EDIT: When I am testing it this is not creating a new functional component (can't use hooks on it).
Here is an example to illustate that myGenericComp1 is not actually creating a new functional component.
t
p
Thanks a lot @turansky I now have a working example using your answer. However, I am not seeing any performance improvements (may be my tests are not sophiscated enough). Anyway, would you mine to explain why I should prefer your method over mine?
t
Anyway, would you mine to explain why I should prefer your method over mine?
Do you mean variants with component and without component?
p
Do you mean variants with component and without component?
No, I don't. I was talking about variants between what I originally posted (i.e. a lambda functional component) and what you provided (i.e. a standard generic functional component).
Copy code
fun <T> myGenericComp() = { props: MyGenericCompProps<T> ->
    buildElement {
        div {
            +"Generic component"
        }
    }
}
t
myGenericComp
in your example - new component every call AFAIK Kotlin will create anonymous function for lambda, but it’s implementation details, which only hide problem
p
Ok thanks for the information. I supposed that it was the problem but I wanted confirmation because I wasn't able to detect any difference between the two methods even with hundreds of components and mutiple state changes.
🚀 1