react
[React] input태그 Enter키 이벤트
현이승
2023. 3. 25. 14:53
react에서 게시글에 댓글을 작성할 수 있는 기능을 개발하고자 했다.
input태그에서 텍스트를 입력하고 게시 버튼을 클릭하면 댓글이 작성되도록 만들었는데 Enter키를 눌렀을때도 같은 동작을 할 수 있도록 하고싶었다.
다른 페이지에서도 이를 활용할 가능성이 있어 Custom hook으로 빼서 개발을 진행하였다.
호출하는 부분
const [comment, setComment] = useState<string>("");
const { buttonRef, handleKeyDown} = useBtnWithEnter(EventCommentCreate); // 커스텀 훅
/* 댓글 달기 Event */
const EventCommentCreate = () =>{
통신하는 부분 ...
setComment(""); // 통신 성공시 초기화
};
/* 댓글 input창 onChange */
const onChangeComment = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
setComment(e.target.value);
}, [comment]);
...
<div>
<input
type="text"
placeholder="댓글 달기"
name="comment"
value={comment}
onChange={onChangeComment}
onKeyDown={(e) => handleKeyDown(e)}
></input>
<ComentSendBtn
ref={buttonRef}
onClick={()=> EventCommentCreate()}
>게시</ComentSendBtn>
</div>
처음 커스텀 훅을 정의할때 EventCommentCreate를 인자로 넘겼다.
input 태그에서는 onKeyDown 이벤트를 사용하여 커스텀 훅에 handleKeyDown을 호출,
게시 button 에서는 onClick 이벤트를 사용하여 EventCommentCreate를 호출하였다.
useBtnWithEnter 커스텀 훅 코드
import { useRef, KeyboardEvent } from "react";
export function useBtnWithEnter(callback: () => void) {
const buttonRef = useRef(null) as React.MutableRefObject<any>;
function handleKeyDown(e : KeyboardEvent<HTMLInputElement>) {
if(e.key === 'Enter' && buttonRef.current){
callback();
}
}
return { buttonRef, handleKeyDown};
};
Enter 키 이벤트가 발생했을 때 HTML 버튼 요소가 존재하면 인자로 넘겼던 callback 함수를 호출하였다.
buttonRef는 없어도 잘 동작하지만 의도하지 않은 동작을 유발할 수 있어 추가하였다.
만약 EventCommentCreate 이벤트에 파라미터가 있다면 handleKeyDown 함수에서 이벤트와 파라미터를 같이 받아 진행하면 된다.