트위터 클론코딩 - 2.router

이예·2022년 12월 10일
0

React

목록 보기
14/21
post-thumbnail

다음과 같이 components 폴더와 routes 폴더 생성하여 관리
파일 관리 이미지 components 폴더에 App.js, Router.js를 생성하고, routes 폴더에 Auth.js, EditProfile.js, Home.js, Profile.js를생성한다.

js 내용은

import React from "react";

const 파일명 = () => <span>파일명</span>
export default 파일명;

npm i react-router-dom react-router-dom 설치

강의에서는 router-domdl 5버전이지만 6버전으로 사용한다. 해당 부분에서 발생하는 에러는 error 카테고리에 업로드 예정이다

Router.js
로그인이 되어있다면 /경로에 Home 내용 표시,
되어있지 않다면 /경로에 Auth 내용 표시

/* eslint-disable import/no-anonymous-default-export */
import React, { useState } from "react";
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import Auth from "../routes/Auth";
import Home from "../routes/Home";

 const AppRouter = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    return(
        <Router>
            <Routes>
                {isLoggedIn ?
                <Route exact path="/" element={<Home/>}/>
                 : <Route exact path="/" element={<Auth/>} />}
            </Routes>
        </Router>
    )

};

export default AppRouter;

App.js
AppRouter 컴포넌트 호출하여 해당 경로일 때 컴포넌트가 잘 출력되는지 확인

function App() {
  return (
    <AppRouter />
  );
}

npm run start
코드 실행화면
로그인을 하지 않았기 때문에 (= isLoggedIn의 값을 false로 설정했기 때문에) Auth 컴포넌트의 내용인 출려되는걸 확인할 수 있다.

const [isLoggedIn, setIsLoggedIn] = useState(false);해당 부분의 false를 true로 바꿔 isLoggedIn을 true로 설정하면

Home 컴포넌트 내용이 출력되는 것을 확인할 수 있다.

profile
다 해보고싶은 사람

0개의 댓글