Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,16 @@ export function useProps<T extends Record<string, any>>(
) {
const [local, instanceProps] = splitProps(props, ["ref", "args", "object", "attach", "children"])

// Assign the ref before mounting children, so a child can read this element's ref
// in a reactive binding during its own render — matching Solid DOM, which assigns
// refs before inserting children (see the "ref timing" test).
createRenderEffect(() => {
const object = resolve(accessor)
if (!object) return
if (local.ref instanceof Function) local.ref(object)
else local.ref = object
})

useSceneGraph(accessor, props)

createRenderEffect(() => {
Expand All @@ -384,12 +394,6 @@ export function useProps<T extends Record<string, any>>(
if (childMeta) childMeta.ctx = context as Context
}

// Assign ref
createRenderEffect(() => {
if (local.ref instanceof Function) local.ref(object)
else local.ref = object
})

// Apply the props to THREE-instance
createRenderEffect(() => {
const keys = Object.keys(instanceProps)
Expand Down
34 changes: 34 additions & 0 deletions tests/core/ref-timing.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createRenderEffect } from "solid-js"
import * as THREE from "three"
import { describe, expect, it } from "vitest"
import { createT } from "../../src/index.ts"
import { test } from "../../src/testing/index.tsx"

const T = createT(THREE)

describe("ref timing", () => {
// Matches Solid DOM: a parent's ref must be assigned BEFORE its children mount,
// so a child can read the parent ref in a reactive binding during its own render.
it("a child sees the parent's ref during its own render", () => {
let parent: THREE.Mesh | undefined
let seenByChild: THREE.Object3D | undefined

const Child = (props: { parent: () => THREE.Mesh | undefined }) => {
// Runs during the child's creation, like a reactive prop binding would.
createRenderEffect(() => (seenByChild = props.parent()))
return <T.MeshBasicMaterial />
}

test(() => (
<T.Mesh ref={parent}>
<T.BoxGeometry args={[2, 2]} />
<Child parent={() => parent} />
</T.Mesh>
))

expect({ parentAssigned: parent != null, childSawParent: seenByChild === parent }).toEqual({
parentAssigned: true,
childSawParent: true,
})
})
})
Loading