1. "정말로 이 페이지를 나가시겠습니까?"
가끔 길고 긴 회원가입 칸을 적어나가다, 실수로 "뒤로가기" 를 누를 때가 있다.
절망에 빠지지 않도록 Prompt 를 사용해서 한번 물어보도록 하자.
2. Prompt
Prompt 는, 유저의 행동을 추적해, 페이지에서 벗어나려 하는지 확인한다.
그리고 벗어나려 한다면, 준비된 코드를 실행한다.
import { Prompt } from "react-router-dom"
Prompt : "렌더" 하는 요소로,
1) when : 언제 Prompt 를 실행시킬지(참이라면 실행)
2) message : 무슨 말을 할까
<Prompt when={focused} message={(location) => "정말로 나가시겠습니까?"} />
3. onFocus 이벤트 리스너
onFocus 는 유저가 인풋을 클릭하고, 나면 true 를 반환한다.
4. 유저가 칸을 클릭하고나서, 뒤로 가려하면, Prompt 로 한번 물어보는 코드를 만들자.
import { Prompt, useHistory } from "react-router-dom";
const Component = () => {
const submitHandler = (e) => { // 제출 핸들러
e.preventDefault();
const quotes = {
id: idState,
author: authorState,
content: contentState,
};
dispatch(quotesActions.addQuotes({ quotes }));
history.replace("/quotes");
};
const onFocusHandler = () => { // 뒤로가기 물어보기
setFocused(true);
};
const deleteFocusHandler = () => { // 제출할때는 focuse 제거하여, Prompt 안나오게
setFocused(false);
};
return (
<Fragment>
<Prompt when={focused} message={(location) => "정말로 나가시겠습니까?"} />
<form onFocus={onFocusHandler} onSubmit={submitHandler}> // form 에 submit 을 달아놓아야
<div>
<label htmlFor={"id"}> 아이디 </label>
...
value={contentState}
onChange={(e) => contentInputHandler(e)}
/>
</div>
<div>
<button onClick={deleteFocusHandler}> 추가하기 </button> // 제출 직전, focus 를 없애, Prompt 의 실행을 막는다
</div>
</form>
</Fragment>
** 제출할때 Prompt 가 나오지 않게 하기 위해, 버튼 에 클릭리스너로, Foucs 를 없앤다.
** 그러므로, SubmitHandler 는 Form 에 달아야한다.
'React > React-Route' 카테고리의 다른 글
7. V6 업그레이드 방법 기초(1) (0) | 2022.12.22 |
---|---|
6. useHistory, 복잡한 쿼리매개변수와 path 를 가지고 있을 때, 사용방법 (0) | 2022.12.22 |
4. 잘못된 URL 주소로 들어간다면, Not Found Page 돌려주기 (1) | 2022.12.22 |
3. 쿼리 매개변수를 사용해, 아이템 정렬하기 [ useHistory, useLocation , URLSearchParams ] (0) | 2022.12.20 |
2. React-Route의 기본 사용(2) v5 (0) | 2022.12.20 |
댓글