S
SolidJS14mo ago
aryzing

How to pass reactive values to `ref`?

For example, inside a <For> element, how would the ref handle using For's reactive index? Something like the code below (which doesn't work),
<For each={items}>
{(_item, i) => <div ref={el => someFnThatNeedsIndex(i())}></div>}
</For>
<For each={items}>
{(_item, i) => <div ref={el => someFnThatNeedsIndex(i())}></div>}
</For>
3 Replies
foolswisdom
foolswisdom14mo ago
You can either:
<For each={items}>
{(_item, i) => <div ref={el => createEffect(() => someFnThatNeedsIndex(i()))}></div>}
</For>
<For each={items}>
{(_item, i) => <div ref={el => createEffect(() => someFnThatNeedsIndex(i()))}></div>}
</For>
or
<For each={items}>
{(_item, i) => <div ref={el => someFnThatNeedsIndex(i)}></div>}
</For>
<For each={items}>
{(_item, i) => <div ref={el => someFnThatNeedsIndex(i)}></div>}
</For>
and rewrite someFnThatNeedsIndex to take a signal as the argument, and call the signal internally when it needs the latest value If it's fine to call someFnThatNeedsIndex multiple times, then you might use the first option, otherwise you'll need to use the second option This is true for other custom primitives as well, you need to pass the signal so the primitive is able to access the latest value (For many props, excluding those starting with on and the ref prop, the generated code is pretty much equivalent to the first solution)
aryzing
aryzingOP14mo ago
Thanks @foolswisdom , I'll try it out @foolswisdom thanks again, was able to modify the code to fit my needs. The key was wrapping the function with createEffect() ✅ . Wasn't aware that it could be called in this context
foolswisdom
foolswisdom14mo ago
Great
Want results from more Discord servers?
Add your server