Hi I am labbing with this code snippet and want to use it in Typescript but it complains about the useRef type and many more. Most importantly: it doesn't allow the next.focus();. It just says "Property 'focus' does not exist on type 'never'.ts(2339)"
Is it "not ok" in typescript to use the .focus() or do it want me to use onFocus or something?
The link to the Sandbox: https://codepen.io/vitalyq/pen/GRNXmQY?editors=0011
Here's the code in just React:
function useFocusNext() {
const controls = useRef([]);
const handler = (event) => {
if (event.keyCode === 13) {
const index = controls.current.indexOf(event.target);
const next = controls.current[index + 1];
next && next.focus();
// IE 9, 10
event.preventDefault();
}
};
return useCallback((element) => {
if (element && !controls.current.includes(element)) {
controls.current.push(element);
element.addEventListener('keydown', handler);
}
}, []);
};
function Form() {
const focusNextRef = useFocusNext();
const [showMore, setShowMore] = useState(false);
const toggleMore = () => setShowMore((last) => !last);
return (
<>
<input ref={focusNextRef} placeholder="Field 1" />
{showMore && <>
<input ref={focusNextRef} placeholder="Added Field" />
</>}
<input ref={focusNextRef} placeholder="Field 2" />
<button ref={focusNextRef}>Submit</button>
<button onClick={toggleMore}>Toggle More Fields</button>
</>
);
};
ReactDOM.render(
<Form />,
document.getElementById('root')
);
And here's my code trying to transform it
const useFocusNext = () => {
const controls: MutableRefObject<never[]> = useRef([]);
const handler = (event: {
keyCode: number;
target: any;
preventDefault: () => void;
}) => {
if (event.keyCode === 13) {
if(event && event.target) {
const index: number = controls.current.indexOf(event.target as never);
const next = controls.current[index + 1];
if (next) {
next.focus();
}
}
// IE 9, 10
event.preventDefault();
}
};
return useCallback((element) => {
if (element && !controls.current.includes(element as never)) {
controls.current.push(element as never);
element.addEventListener("keydown", handler);
}
}, []);
};