React
Link to, history를 사용하기
jennyiscoding
2022. 12. 4. 13:39
1) Link to 쓰기
<Link to="/">Back to Home</Link>
2) history를 쓰기
const submitForm = e => {
e.preventDefault();
const email = emailRef.current.value;
const password = passwordRef.current.value;
// DetailPage로 이동하는 코드를 작성하세요.
history.push(`/detail?email=${email}&password=${password}`);
};
그러면은 url에 쿼리로 내가 입력한 값이 들어간다.
React App
ezpxu7uua99m6xckveo8fc4ymi4uyzib.runner-forwarder-a-02.elice.io
detail페이지에서는 이렇게 쿼리 값을 가져올 수 있다.
const location = useLocation();
const searchParams = new URLSearchParams(location.search);
const email = searchParams.get('email');
const password = searchParams.get('password');
if (!email || !password) {
return <Redirect to="/login" />;
}
3)
const history = useHistory();
const handleSubmit = formData => {
const { email } = formData;
const foundUser = users.find(list => list.email === email);
if (foundUser) {
alert('이미 등록된 유저입니다');
} else {
users.push(formData);
history.push('/login');
}
};
4) detail페이지
const handleSubmit = formData => {
const { email, password } = formData;
const founduser = users.find(
user => user.email === email && user.password === password
);
if (founduser) {
history.push(`/detial?email=${email}&password=${password}`);
}
};