11.08 항해 57일차 TIL

한우석·2021년 11월 8일
0

라우터 분리

header에서 버튼 클릭 시 아이콘을 변경 해야 했었는데 Header이 아래처럼 설정 되어 있어서 Router를 분리해야 더 깔끔한 코드가 될 것 같아서 분리 하는법을 찾아보았다.

//App.js
</Route>
  <Route path="/contap" exact>
    <Permit>
      <Header />
        <Contap />
    </Permit>
  </Route>
  <Route path="/mypage" exact>
    <Permit>
      <Header />
        <Mypage />
    </Permit>
  </Route>
  <Route path="/edit" exact>
    <Permit>
      <Header />
        <CardEdit />
    </Permit>
  </Route>

구글링을 해서 방법을 찾아보니 크게 어렵진 않아서 바로 적용을 해보았다.

// PublicRoute.js
import React from 'react';
import { Redirect, Route } from 'react-router';
import isLogin from '../utils/isLogin';

const PublicRoute = ({ component: Component, restricted, ...rest }) => {
  console.log(isLogin());
  return (
    <Route
      {...rest}
      render={(props) =>
        isLogin() && restricted ? <Redirect to="/" /> : <Component {...props} />
      }
    />
  );
};

export default PublicRoute;

//PrivatecRoute.js
import React from 'react';
import { Redirect, Route } from 'react-router';
import isLogin from '../utils/isLogin';

const PrivatecRoute = ({ component: Component, ...rest }) => {
  console.log(isLogin())
  return (
    <Route
      {...rest}
      render={(props) =>
        isLogin() ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
};

export default PrivatecRoute;

//App.js
function App() {
  return (
    <FullWrap>
      <Wrap>
        <Reset />
        <PublicRoute restricted path="/login" component={Login} exact />
        <PublicRoute restricted path="/signup" component={Signup} exact />
        <>
	        <Header />
	        <Permit>
	          <PublicRoute path="/" component={CardList} exact />
	          <PrivatecRoute path="/settings" component={Settings} exact />
	          <PrivatecRoute path="/contap" component={Contap} exact />
	          <PrivatecRoute path="/mypage" component={Mypage} exact />
	          <PrivatecRoute path="/edit" component={CardEdit} exact />
	        </Permit>
        </>
      </Wrap>
    </FullWrap>
  );
}

확실히 뭔가 정돈 된 느낌이라 되게 만족스러웠다 ㅎ..

profile
H/W 개발자에서 프론트 엔드 개발자로 전향 하고 있는 초보 개발자

0개의 댓글