반응형

들어가며

  • 아래 예제는 v6.15.0 버전을 기준으로 작성됨

react-router-dom 설치

yarn add react-router-dom

기본 예제

src/App.js

import React from 'react';
import {createBrowserRouter, RouterProvider} from "react-router-dom";
import Root from "./Root";
import Error from "./Error";

const router = createBrowserRouter([
    {
        path: "/",
        element: <Root/>,
        errorElement: <Error/>,
    },
]);

const App = () => {
    return (
        <RouterProvider router={router}/>
    );
}

export default App;

src/Root/index.js

import React from 'react';

const Root = () => {
    return <div>Root</div>;
};

export default Root;

src/Error/index.js

import React from 'react';
import {useRouteError} from "react-router-dom";

const Error = () => {
    const error = useRouteError();
    console.error(error);

    return <div>
        <h1>Error</h1>
        <p>
            <i>{error.statusText || error.message}</i>
        </p>
    </div>
};

export default Error;

Old Version

들어가기 전

  • BrowserRouter 자식이 하나가 아닐 경우 오류 발생

react-router-dom 설치

yarn add react-router-dom

App.css

.header {
  background: #5c7cfa;
  display: table;
  table-layout: fixed;
  width: 100%;
}

.item {
  text-align: center;
  padding-top: 1rem;
  padding-bottom: 1rem;
  display: table-cell;
  color: white;
  text-decoration: none;
  font-size: 1.1rem;
}

.item:hover {
  background: #748ffc;
}

.item:active, .item.active {
  background: white;
  color: #5c7cfa;
}

Basic Example

App.js

import React from 'react';
import {BrowserRouter as Router, NavLink, Route, Switch} from "react-router-dom";
import './App.css';

const Home = () => {
    return (
        <div>
            Home
        </div>
    )
};

const Example = () => {
    return (
        <div>
            Example
        </div>
    )
};

function App() {
    return (
        <Router>
            <div>
                <div className="header">
                    <NavLink exact to="/" className="item" activeClassName="active">Home</NavLink>
                    <NavLink to="/example" className="item" activeClassName="active">Example</NavLink>
                </div>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/example" component={Example}/>
                </Switch>
            </div>
        </Router>
    );
}

export default App;

Path Variable Example

App.js

import React from 'react';
import {BrowserRouter as Router, NavLink, Route, Switch} from "react-router-dom";
import './App.css';

const Home = () => {
    return (
        <div>
            Home
        </div>
    )
};

// this.props.match
const Example = ({match}) => {
    return (
        <div>
            Example : {match.params.username}
        </div>
    )
};

function App() {
    return (
        <Router>
            <div>
                <div className="header">
                    <NavLink exact to="/" className="item" activeClassName="active">Home</NavLink>
                    <NavLink to="/example/john" className="item" activeClassName="active">Example</NavLink>
                </div>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/example/:username" component={Example}/>
                </Switch>
            </div>
        </Router>
    );
}

export default App;

테스트

  • URL 접속 : http://localhost:3000/example/john
  • Example : john이라고 뜨는지 확인

Query String Example

App.js

import React from 'react';
import {BrowserRouter as Router, NavLink, Route, Switch} from "react-router-dom";
import './App.css';

const Home = () => {
    return (
        <div>
            Home
        </div>
    )
};

const Example = ({location}) => {
    return (
        <div>
            Example : {new URLSearchParams(location.search).get("keyword")}
        </div>
    )
};

function App() {
    return (
        <Router>
            <div>
                <div className="header">
                    <NavLink exact to="/" className="item" activeClassName="active">Home</NavLink>
                    <NavLink to="/example" className="item" activeClassName="active">Example</NavLink>
                </div>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/example" component={Example}/>
                </Switch>
            </div>
        </Router>
    );
}

export default App;

테스트

  • URL 접속 : http://localhost:3000/example?keyword=aaa
  • Example : aaa 라고 잘 뜨는지 확인

Route Programmatically Example

App.js

import React from 'react';
import {BrowserRouter as Router, NavLink, Route, Switch} from "react-router-dom";
import './App.css';

const Home = () => {
    return (
        <div>
            Home
        </div>
    )
};

const Example = ({history}) => {
    return (
        <div>
            <button onClick={() => history.push('/')}>Home으로 이동</button>
        </div>
    )
};

function App() {
    return (
        <Router>
            <div>
                <div className="header">
                    <NavLink exact to="/" className="item" activeClassName="active">Home</NavLink>
                    <NavLink to="/example" className="item" activeClassName="active">Example</NavLink>
                </div>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/example" component={Example}/>
                </Switch>
            </div>
        </Router>
    );
}

export default App;

테스트

  • URL 접속 : http://localhost:3000/example
  • Home으로 이동 버튼 클릭시 홈으로 이동하는지 확인

Rediect Example

App.js

import React from 'react';
import {BrowserRouter as Router, NavLink, Route, Switch, Redirect} from "react-router-dom";
import './App.css';

const Home = () => {
    return (
        <div>
            Home
        </div>
    )
};

const Example = () => {
    return (
        <div>
            Example
            {
                <Redirect to="/"/>
            }
        </div>
    )
};

function App() {
    return (
        <Router>
            <div>
                <div className="header">
                    <NavLink exact to="/" className="item" activeClassName="active">Home</NavLink>
                    <NavLink to="/example" className="item" activeClassName="active">Example</NavLink>
                </div>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/example" component={Example}/>
                </Switch>
            </div>
        </Router>
    );
}

export default App;

테스트

  • URL 접속 : http://localhost:3000/example
  • http://localhost:3000/로 이동하는지 확인

Not Found Page Example

App.js

import React from 'react';
import {BrowserRouter as Router, NavLink, Route, Switch} from "react-router-dom";
import './App.css';

const Home = () => {
    return (
        <div>
            Home
        </div>
    )
};

const Example = () => {
    return (
        <div>
            Not Found Page
        </div>
    )
};

function App() {
    return (
        <Router>
            <div>
                <div className="header">
                    <NavLink exact to="/" className="item" activeClassName="active">Home</NavLink>
                </div>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route component={Example}/>
                </Switch>
            </div>
        </Router>
    );
}

export default App;

테스트

  • URL 접속 : http://localhost:3000/aaa
  • Not Found Page 페이지가 나타나는지 확인

참고

반응형

'Development > React' 카테고리의 다른 글

[React] useContext  (0) 2019.05.23
[React] Storybook  (0) 2019.05.20
[React] CSS Module  (0) 2019.05.16
[React] Hooks  (0) 2019.05.15
[React] MobX  (0) 2019.05.14

+ Recent posts