트위터 클론 코딩 - 6. 로그아웃

이예·2022년 12월 14일
0

React

목록 보기
18/21

네비게이션(메뉴)를 만들어서 프로필로 가면 로그아웃 버튼이 있게 작성

component에 Navigation.js 생성
react-router-dom의 Link태그를 사용하여 페이지 이동

import React from "react";
import {Link} from "react-router-dom";

const Navigation = () => <nav>
    <ul>
        <li>
            <Link to="/">Home</Link>
        </li>
        <li>
            <Link to="/profile">My Profile</Link>
        </li>
    </ul>
</nav>;

export default Navigation;

Router.js
로그인 되어있으면 네비게이션(메뉴) 출력하도록 코드 추가
<Route> 프로필 path 추가

const AppRouter = ({isLoggedIn}) => {
  return(
    <Router>
      {isLoggedIn && <Navigation />}
      <Routes>
        {isLoggedIn ?
        <>
          <Route exact path="/" element={<Home/>}/>
          <Route exact path="/profile" element={<Profile/>}/>
        </>
        : <Route exact path="/" element={<Auth/>} />}
      </Routes>
    </Router>
)

};

실행하면 다음과 같은 네비게이션이 출력된다

My Profile에 signOut 활용하여 로그아웃가능한 버튼 추가
Profile.js

import { authService } from "fBase";
import React from "react";

const Profile = () => {
    const onLogOutClick = () => authService.signOut();

    return(
        <>
            <button onClick={onLogOutClick}>Log Out</button>
        </>
    )
};

export default Profile;

버튼을 누르면 로그아웃되지만 경로가 profile로 되어있기 때문에 footer만 출력된다. 로그아웃을 하면 Home으로 redirect하는 코드를 추가한다

Profile.js
react-router-dom v6에서는 redirect에 useNavigate를 활용한다

import { authService } from "fBase";
import React from "react";
import { useNavigate } from "react-router-dom";

const Profile = () => {
  const navigate = useNavigate();

  const onLogOutClick = () => {
    authService.signOut();
    navigate("/");
  }
  return(
    <>
      <button onClick={onLogOutClick}>Log Out</button>
    </>
  )
};

export default Profile;



버튼을 클릭하면 다음과 같이 Home으로 redirect 된 것을 확인할 수 있다.

profile
다 해보고싶은 사람

0개의 댓글