S
SolidJS16mo ago
Mathieu

Add a ref and make it also exposable

To create a ref, I can write:
<input ref={ref} />
<input ref={ref} />
In order to expose it to a parent component, I can write:
<input ref={props.ref} />
<input ref={props.ref} />
But what if I want both? Say I have a TextField component. I want to add a ref to the input field (for internal use inside TextField), but I also want a parent to be able to access the ref.
12 Replies
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
Mathieu
Mathieu16mo ago
@snnsnn how would I make it exposable for the parent with a function?
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
Mathieu
Mathieu16mo ago
oh so the parent passes a callback. I see I'll try that, bbl:)
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
REEEEE
REEEEE16mo ago
you should also be able to do
<input ref={el => {props.ref = el; ref = el;}} />
<input ref={el => {props.ref = el; ref = el;}} />
mdynnl
mdynnl16mo ago
ref prop is always a callback even for <div ref={div} /> it's just that it's specially compiled to assign the node to passed identifier if it does not hold a function so it should be something like ref={el => props.ref(ref = el)}
Mathieu
Mathieu16mo ago
ref={el => props.ref?.(inputRef = el)}
ref={el => props.ref?.(inputRef = el)}
I have the following error:
This expression is not callable. Type 'HTMLInputElement' has no call signatures.
mdynnl
mdynnl16mo ago
we have Ref type helper i think type Ref<T> = T | ((ref:T) => void)
Otonashi
Otonashi16mo ago
just type cast it when assigning refs you can use either but when accessing the prop it's always the callback but it's impossible to type the same thing differently in those two contexts
Mathieu
Mathieu16mo ago
ref={el => (props.ref as any)?.(inputRef = el)}
ref={el => (props.ref as any)?.(inputRef = el)}
n any better way than any? never mind, I have better luck with that style:
ref={el => {props.ref = el; inputRef = el;}}
ref={el => {props.ref = el; inputRef = el;}}
much less headaches for some reason
Otonashi
Otonashi16mo ago
props.ref as ((el: HTMLInputElement) => void) | undefined
Want results from more Discord servers?
Add your server