Is there a way to pre-render a component, and then...
# react
z
Is there a way to pre-render a component, and then conditionally include it in the render? In TypeScript, I can set a variable to some JSX output, and then use that during the render of an outer functional component, like a div wrapper.
Copy code
function Example() {
    const someCondition = true;
    const someOtherCondition = true;
    const someComponent = (<p>some component</p>);
    const someOtherComponent = (<p>some other component</p>);
    return (<>
        <div>{someCondition && someComponent}</div>
        <div>{someOtherCondition && someOtherComponent}</div>
    </>);
}
Using a direct translation in Kotlin renders things out of order, the p before the div, and since the react functions are mutators, not factories, they only return Unit
Copy code
val Example = FC {
    val someCondition = true
    val someOtherCondition = true
    val someComponent: Unit = p { +"some component" }
    val someOtherComponent: Unit = p { +"some other component" }

    div { if (someCondition) { @Suppress("UNUSED_EXPRESSION") someComponent } }
    div { if (someOtherCondition) { @Suppress("UNUSED_EXPRESSION") someOtherComponent } }
}
In my specific case, I need to render a component in one of two containers, depending on some current state. Like a
<details>
with a
name
so only one in a group can be open at once. The only ways I've found so far are to either duplicate the unused div, or render the same component in both blocks like so.
Copy code
if (someCondition) {
    div { p { +"some component" } }
    div { p { +"some other component" } }
}
else if (someOtherCondition) {
    div { p { +"some other component" } }
    div { p { +"some component" } }
}
// or
div {
    if (someCondition) {
        p { +"some component" }
    }
    else if (someOtherCondition) {
        p { +"some other component" }
    }
}
div {
    if (someOtherCondition) {
        p { +"some component" }
    }
    else if (someCondition) {
        p { +"some other component" }
    }
}
The thing I'm most trying to avoid is wordy FC creation, on things more complicated than a
p
Or maybe as an alternative, is it possible to reparent a child component depending on some condition?
t
Please use
create
factory method to create React elements:
Copy code
val Example = FC {
    val someCondition = true
    val someOtherCondition = true
    val someComponent = p.create { +"some component" }
    val someOtherComponent = p.create { +"some other component" }

    div { 
        if (someCondition) { 
            +someComponent 
        } 
    }

    div { 
        if (someOtherCondition) { 
            +someOtherComponent
        }
    }
}
1