vlk
vlk

Reputation: 1454

React hook useRef not working with styled-components and typescript

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:

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}/>
  );
}

Upvotes: 25

Views: 18123

Answers (3)

Connor M
Connor M

Reputation: 341

As an alternative to the current accepted answer, you can also do:

const inputRef = useRef<HTMLInputElement>(null);

Upvotes: 7

vlk
vlk

Reputation: 1454

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}/>
  );
}

Upvotes: 26

Carwyn Stephen
Carwyn Stephen

Reputation: 134

Pass your inputRef in the array argument of useEffect and let's see if that works, you aren't guaranteed to have a .current in your ref, so you should run the effect every time inputRef changes

Upvotes: 0

Related Questions