[TypeScript] 'textRef.current' is possibly 'null'.ts(18047)

Rachaen·2023년 3월 19일
0

'textRef.current' is possibly 'null'.ts(18047) 오류

import React, { useCallback, useRef } from 'react';
import styles from '@/styles/snack_detail.module.css';
export default function Comment() {
  const textRef = useRef<HTMLTextAreaElement>(null);
  const handleResizeHeight = useCallback(() => {
    textRef.current.style.height = 'auto';
    textRef.current.style.height = textRef.current.scrollHeight + 'px';
  }, []);
  return (
    <textarea
      rows={1}
      ref={textRef}
      className={styles.content_text}
      placeholder='게시글 입력하기..'
      onInput={handleResizeHeight}
    />
  );
}

해결

방법1. any사용

import React, { useCallback, useRef } from 'react';
import styles from '@/styles/snack_detail.module.css';
export default function Comment() {
  const textRef = useRef<any>(null);
  const handleResizeHeight = useCallback(() => {
    textRef.current.style.height = 'auto';
    textRef.current.style.height = textRef.current.scrollHeight + 'px';
  }, []);
  return (
    <textarea
      rows={1}
      ref={textRef}
      className={styles.content_text}
      placeholder='게시글 입력하기..'
      onInput={handleResizeHeight}
    />
  );
}

typescript에서 any를 사용하는 건 아니라 생각해서.. 두번째 방법으로...

방법2. 조건문

import React, { useCallback, useRef } from 'react';
import styles from '@/styles/snack_detail.module.css';
export default function Comment() {
  const textRef = useRef<HTMLTextAreaElement>(null);
  const handleResizeHeight = useCallback(() => {
    if (textRef && textRef.current) {
      textRef.current.style.height = 'auto';
      textRef.current.style.height = textRef.current.scrollHeight + 'px';
    }
  }, []);
  return (
    <textarea
      rows={1}
      ref={textRef}
      className={styles.content_text}
      placeholder='댓글 남기기'
      onInput={handleResizeHeight}
    />
  );
}

참고1 TypeScript: React useRef Hook

참고2: how-to-fix-object-is-possibly-null-typescript

profile
개발을 잘하자!

0개의 댓글