본문 바로가기
React

Link to, history를 사용하기

by jennyiscoding 2022. 12. 4.

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에 쿼리로 내가 입력한 값이 들어간다. 

https://ezpxu7uua99m6xckveo8fc4ymi4uyzib.runner-forwarder-a-02.elice.io/detail?email=dd&password=dddd 

 

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}`);
    }
  };

'React' 카테고리의 다른 글

/* eslint-disable @typescript-eslint/no-use-before-define */  (0) 2023.10.04
confirm 사용방법  (0) 2023.01.30
메타테그란?  (0) 2022.11.15
배포했는데 갑자기 오류가 났다..  (0) 2022.09.02
드롭다운메뉴바 구현 코드  (0) 2022.08.22