'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}
/>
);
}
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를 사용하는 건 아니라 생각해서.. 두번째 방법으로...
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