Ref either locally or passed via prop

I have a TextField that requires a ref to an input field.
let input: HTMLInputElement | undefined

return <div onClick={() => input?.focus()}><input ref={input} /></div>
let input: HTMLInputElement | undefined

return <div onClick={() => input?.focus()}><input ref={input} /></div>
So far so good. But in case I have a parent component that also wants to ref the input, I am no longer sure how to handle it. I have something like this
let input: HTMLInputElement | undefined

return <div onClick={() => ('ref' in props ? props.ref : input)?.focus()}><input ref={'ref' in props ? props.ref : input}/></div>
let input: HTMLInputElement | undefined

return <div onClick={() => ('ref' in props ? props.ref : input)?.focus()}><input ref={'ref' in props ? props.ref : input}/></div>
This works for outer ref, but breaks fallback inner ref. What is the correct way to handle this case? ❤️
3 Replies
Alex Lohr
Alex Lohr2y ago
GitHub
solid-primitives/README.md at main · solidjs-community/solid-primit...
A library of high-quality primitives that extend SolidJS reactivity. - solid-primitives/README.md at main · solidjs-community/solid-primitives
Alex Lohr
Alex Lohr2y ago
But if you want to do it manually, use a signal for the ref and wrap the setter so that it will also call props.ref?.(node).
const Component = (props) => {
const [ref, _setRef] = createSignal<HTMLInputElement>();
const setRef = (node) => { props.ref?.(node); return _setRef(node); };
return <div onClick={ref()?.focus()}><input ref={setRef} /></div>;
}
const Component = (props) => {
const [ref, _setRef] = createSignal<HTMLInputElement>();
const setRef = (node) => { props.ref?.(node); return _setRef(node); };
return <div onClick={ref()?.focus()}><input ref={setRef} /></div>;
}
Martnart
MartnartOP2y ago
Much appreciated. Thank you. I'll have a look at the primitive 🙂
Want results from more Discord servers?
Add your server