Add a ref and make it also exposable
To create a ref, I can write:
In order to expose it to a parent component, I can write:
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•16mo ago
Message Not Public
Sign In & Join Server To View
@snnsnn how would I make it exposable for the parent with a function?
Unknown User•16mo ago
Message Not Public
Sign In & Join Server To View
oh so the parent passes a callback. I see
I'll try that, bbl:)
Unknown User•16mo ago
Message Not Public
Sign In & Join Server To View
you should also be able to do
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)}
I have the following error:
This expression is not callable. Type 'HTMLInputElement' has no call signatures.
we have
Ref
type helper i think
type Ref<T> = T | ((ref:T) => void)
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
n
any better way than
any
?
never mind, I have better luck with that style:
much less headaches for some reasonprops.ref as ((el: HTMLInputElement) => void) | undefined