Zyle Moore
12/17/2024, 10:02 PMfunction 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
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.
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" }
}
}
Zyle Moore
12/17/2024, 10:35 PMp
Zyle Moore
12/17/2024, 11:00 PMturansky
12/18/2024, 1:46 AMcreate
factory method to create React elements:
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
}
}
}