Styled-Components useRef

 

Styled-Components Ref


Styled-Components로 만든 컴포넌트에 ref를 사용하고 싶었으나 타입스크립트 에러 때문에 안되는 상황.

 

검색을 해보면 별도의 컴포넌트를 만들어 해당 컴포넌트를 기반한 스타일드 컴포넌트로 만들어 사용하고  forwardRef를 사용해 Ref를 전달 후 할당하는 방법 밖에 나오지 않았다.

 

분명 스타일드 컴포넌트에 ref를 바로 선언해 사용 할 수 있을거라 생각해 스택오버플로우를 다 뒤져봤다. 그랬더니  나와같은 상황을 겪은 분을 찾아 코드를 가져왔다.

 

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

 

위 처럼 input을 기반한 StyledInput 컴포넌트를 만들어 사용하고 ref속성에 inputRef를 할당하고 싶었으나 타입에러가 발생함. 

 

해결방법


const inputRef = useRef(null) as React.RefObject<HTMLInputElement>;

 

 

 

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 re...

stackoverflow.com