Forward ref downstream

How can I forward a HTMLElement reference to a downstream component? i.e:
<div ref={theDiv}>
<MyComponent refToTheDiv={theDiv}/>
</div>
<div ref={theDiv}>
<MyComponent refToTheDiv={theDiv}/>
</div>
so that I can use the div inside of MyComponent
5 Replies
fabiospampinato
fabiospampinato15mo ago
refs only make sense in general if they are signals, so you can make a signal and then just pass the setter to ref={} and the getter to refToTheDiv={}
Deflaktor
Deflaktor15mo ago
So I can just do
const [theDiv, setTheDiv] = createSignal(null);

return (
<div ref={setTheDiv}>
<MyComponent refToTheDiv={theDiv} />
</div>
);
const [theDiv, setTheDiv] = createSignal(null);

return (
<div ref={setTheDiv}>
<MyComponent refToTheDiv={theDiv} />
</div>
);
? Ok yeah that seems to work. Kinda difficult for me to wrap my head around how that signal setter works in all kinds of contexts.
fabiospampinato
fabiospampinato15mo ago
once the code is compiled a ref is always a function that is called with an element in this case you are giving it the setter, so that's called with the element, so that becomes the value of the signal
Deflaktor
Deflaktor15mo ago
Thanks for the explanation. On one hand it is a genius solution by the framework, on the other hand (for me as a beginner) it seems like some magic is happening behind the scenes.
fabiospampinato
fabiospampinato15mo ago
If you just use a variable and not a signal there's some magic that's happening behind the scenes, that's part of how Solid works for better or for worse
Want results from more Discord servers?
Add your server