+) 참고
1. PrivateRoute 작성
저는 로그인 정보를 localStorage에 저장하는 방법을 사용하고 있습니다. 상황에 맞게 작성하세요.
로그인 정보가 있을 경우 해당 컴포넌트로 이동할 수 있지만, 로그인 정보가 없다면 로그인 페이지로 redirect되도록 해줍니다.
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
function PrivateRoute ({ component: Component, ...rest }) {
return (
<Route
{...rest}
render = {props =>
localStorage.getItem('users')?(
<Component {...props} />
) : (
<Redirect to={{
pathname: '/users/sign_in',
state: {from: props.location}
}}
/>
)
}
/>
)
}
export default PrivateRoute;
2. App.js(최상위 컴포넌트)에 등록
PrivateRoute를 import한 후 로그인 정보가 있을 경우에만 접근할 수 있는 컴포넌트들을 PrivateRoute를 이용해 작성해주시면 됩니다.
import React from 'react';
import {HashRouter as Router, Switch, Route} from 'react-router-dom';
import PrivateRoute from './helpers/PrivateRoute';
import Home from './components/Home';
import SingIn from './components/users/SignIn';
import SignUp from './components/users/SignUp';
function App(props) {
return (
<Router>
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route path="/users/sign_in" component={SingIn}/>
<Route path="/users/sign_up" component={SignUp}/>
</Switch>
</Router>
);
}
export default App;
+ PrivateRoute에 props 전달하기
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
function PrivateRoute ({ component: Component, getRoomList, ...rest }) {
return (
<Route
{...rest}
render = {props =>
localStorage.getItem('users')?(
<Component {...props} getRoomList={getRoomList} />
) : (
<Redirect to={{
pathname: '/users/sign_in',
state: {from: props.location}
}}
/>
)
}
/>
)
}
export default PrivateRoute;
import React from 'react';
import {HashRouter as Router, Switch, Route} from 'react-router-dom';
import PrivateRoute from './helpers/PrivateRoute';
import Home from './components/Home';
import SingIn from './components/users/SignIn';
import SignUp from './components/users/SignUp';
function App(props) {
return (
<Router>
<Switch>
<PrivateRoute exact path="/" component={Home} getRoomList={props.getRoomList} />
<Route path="/users/sign_in" component={SingIn}/>
<Route path="/users/sign_up" component={SignUp}/>
</Switch>
</Router>
);
}
export default App;
'STUDY > React' 카테고리의 다른 글
React | Hooks로 Life Cycle API 구현하기 (0) | 2020.04.16 |
---|---|
React | emoji 사용하기 (0) | 2020.04.15 |
React | React-Redux 비동기 통신(fetch / redux-thunk) (0) | 2020.03.19 |
React | socket.io를 활용한 채팅 (+ Node.js, redux) (6) | 2020.03.18 |
React | 이미지 업로드 후 미리보기 (on Change / image preview) (0) | 2020.01.21 |