I've some problem using the useRef
hook with a styled component.
Linter alerts me that Object is possibly 'null'
inside the didMount useEffect
. Any idea about this?
This is not a duplicate for 2 reason:
- The old answer refers to the
ref
used in a class component, that was the only way to use it before React hooks, - The
innerRef
props isn't supported anymore in the current version of styled components.
Here's a sample snippet of my component:
import React, { useRef, useEffect } from 'react';
import styled from 'styled-components';
const StyledInput = styled.input`
background: transparent;
`
const MyForm = () => {
const inputRef = useRef(null);
useEffect(() => {
if (inputRef && inputRef.current) {
inputRef.current.focus(); //Object is possibly 'null'
}
}, []);
return (
<StyledInput ref={inputRef}/>
);
}