React hook useRef not working with styled-components and typescript
I've finally found a solution:
const inputRef = useRef() as React.MutableRefObject<HTMLInputElement>;
It works for me:
import React, { useRef, useEffect } from 'react';
import styled from 'styled-components';
const StyledInput = styled.input`
background: transparent;
`
const MyForm = () => {
const inputRef = useRef() as React.MutableRefObject<HTMLInputElement>;
useEffect(() => {
if (inputRef && inputRef.current) {
inputRef.current.focus();
}
}, []);
return (
<StyledInput ref={inputRef}/>
);
}
As an alternative to the current accepted answer, you can also do:
const inputRef = useRef<HTMLInputElement>(null);