S
SolidJS15mo ago
Mathieu

Ref pointing to the wrong element

I have a component that uses a ref:
let bodyElement: HTMLDivElement;
// Somewhere in the TSX:
<div class={styles.body} ref={bodyElement!}>
let bodyElement: HTMLDivElement;
// Somewhere in the TSX:
<div class={styles.body} ref={bodyElement!}>
Let's say the component is called Foo. I have a parent component rendering Foo twice. The problem is that both refs bodyElement are pointing to the ref in the last Foo component. Inside Foo I log the refs:
onMount(() => {
console.log(bodyElement) // points to the last `bodyElement` in the last Foo
console.log(bodyElement.getBoundingClientRect())
});
onMount(() => {
console.log(bodyElement) // points to the last `bodyElement` in the last Foo
console.log(bodyElement.getBoundingClientRect())
});
and I notice that the logs are pointing to the same element, the last bodyElement (in the last Foo). I could not reproduce the problem in the playground.
3 Replies
Grahf
Grahf15mo ago
Maybe making the ref a signal would help?
Mathieu
MathieuOP15mo ago
I actually just asked ChatGPT and immedtiately found out it's because I declared the ref outside the component... yay
Grahf
Grahf15mo ago
Nice
Want results from more Discord servers?
Add your server