`useRef` with an array of refs
i-am-the-slime opened this issue · 6 comments
I know how to use useRef for a Nullable ref to one element.
Is there a way to achieve something like this? It looks like I might need some mutable Array for this.
Maybe it's an antipattern in the first case?
Hmm.. you could do it if you used FFI to set the ref, because react-basic only supports passing a Ref as the ref prop, but this multi- example is using React's alternative ref api of passing a callback. Something like foreign import input :: forall a. ReactComponent { ref :: EffectFn1 (Ref a) Unit, ... }.
These two options are probably better for most cases, though:
- The array is for convenience purposes and the number of elements is static. Just call
useRefmultiple times. - The list is dynamic, but you can create a component which renders a single input and contains its own
useRef, then map over your array in the parent component.
For 2) how would I get the ref back from the child to the parent? With a callback prop to the child?
I do this right now and I'm not sure I can look at myself in the mirror:
ref: unsafeCoerce (\el -> unsafeArraySetAt i el (unsafeCoerce ref).current)
The ref would be hidden in the child and managed using normal props on the child + useEffect. If you really needed to for some reason, the child could have a prop like innerRef :: Ref and pass that to the inner dom node instead of creating its own.
But then you're kind of back to the original issue
Maybe if you explain the use case a bit I can give a more specific suggestion
I'm going to close this for now. Feel free to ask if you have any more questions.