본문 바로가기
my_lesson/_ReactJS

React-router - Redirect

by boolean 2018. 4. 11.
728x90

ReactJS - Redirect

  • react-router v4 version4
  • sorce code는 이전 문서에서 재활용한다.
  • /...../ 는 생략되었다는 표시임
  • 파란 글씨는 추가된 것임
  • 빨간 글씨는 수정된 것임


  • Redirect I - Simple

    ~cra-router/src/routes$ Login.js

    import React from 'react';


    const Login = () => {

        return (

            <div>

                로그인

            </div>

        );

    };


    export default Login;


    ~cra-router/src/routes$ MyPage.js

    import React from 'react';

    import { Redirect } from 'react-router-dom';


    const logged = true;


    const MyPage = () => {

        return (

            <div>

                {

                    !logged && <Redirect to="/login"/>

                }

                마이페이지

            </div>

        );

    };


    export default MyPage;


    ~cra-router/src$ App.js

    import React  from 'react';

    import { BrowserRouter as Router, Route} from 'react-router-dom';


    import Home from './routes/Home';

    import About from './routes/About';

    import Posts from './routes/Posts';

    import Login from './routes/Login';

    import MyPage from './routes/MyPage';


    import Header from './components/Header';


    const App = () => {

        return (

                <Router>

                    <div>

                        <Header />

                        <Route exact path='/' component={Home} />

                        <Route path='/about/:username' component={About} />

                        <Route path='/posts'  component={Posts} />

                        <Route path='/login'  component={Login} />

                        <Route path='/mypage'  component={MyPage} />

                    </div>

                </Router>

        )

    }


    export default App;


    Redirect II - Using History

    ~cra-router/src/routes$ Home.js
    import React from 'react';

    const Home= ({history}) => {
        return (
                    <div>
                        Home <br />
                        <button onClick={()=>{history.push('posts')}}>go_posts</button>
                    </div>

        )
    }

    export default Home;


    댓글