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 User2y ago
Message Not Public
Sign In & Join Server To View
Mathieu
MathieuOP2y ago
@snnsnn how would I make it exposable for the parent with a function?
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Mathieu
MathieuOP2y ago
oh so the parent passes a callback. I see I'll try that, bbl:)
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
REEEEE
REEEEE2y 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
mdynnl2y 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
MathieuOP2y 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
mdynnl2y ago
we have Ref type helper i think type Ref<T> = T | ((ref:T) => void)
Otonashi
Otonashi2y 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
MathieuOP2y 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
Otonashi2y ago
props.ref as ((el: HTMLInputElement) => void) | undefined
Want results from more Discord servers?
Add your server