react에서 routing기능을 제공해주는 패키지다. 사용방법을 정리해본다.
> npm i react-router-dom
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
import React from 'react';
import { Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
const App = () => {
return (
<div>
<Route path="/" component={Home} exact={true}></Route>
<Route path="/about" component={About}></Route>
</div>
);
}
export default App;
import React from 'react';
import { Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
const App = () => {
return (
<div>
<ul>
<li>
<Link to="/">홈</Link>
</li>
<li>
<Link to="/about">소개</Link>
</li>
</ul>
<hr></hr>
<Route path="/" component={Home} exact={true}></Route>
<Route path="/about" component={About}></Route>
</div>
);
}
export default App;
Route의 패스를 /profile/:username
형태로 선언한다.
<Route path="/profile/:username" component={Profile}></Route>
props.match.params[동적path_이름]
으로 접근 한다.
const Profile = ({ match }) => {
const { username } = match.params;
return (
<div>
<h3>
{username}({profile.name})
</h3>
<p>
{profile.description}
</p>
</div>
);
};
import { useRouteMatch } from 'react-router';
const Profile = () => {
const { params: { username } } = useRouteMatch();
return (
<div>
<h3>
{username}({profile.name})
</h3>
<p>
{profile.description}
</p>
</div>
);
};
// [username].jsx 로 파일 생성
import { useParams } from 'react-router';
const Profile = () => {
const { username } = useParams();
return (
<div>
<h3>
{username}({profile.name})
</h3>
<p>
{profile.description}
</p>
</div>
);
};
props.location.search[쿼리스트링_이름]
으로 접근이 가능하다.
그러나 string 형태로 되어있기에 파싱을 위해 qs 라이브러리를 사용한다.
import React from 'react';
import qs from 'qs';
const About = ({ location }) => {
const query = qs.parse(location.search, {
ignoreQueryPrefix: true // 맨앞 ? 생략
});
const showDetail = query.detail === 'true'
return (
<div>
<h1>소개</h1>
<p>이 프로젝트는 리액트 라우터 기초를 실습해 보는 예제 프로젝트입니다.</p>
{showDetail && <p>Detail 값을 true로 설정하셨군요</p>}
</div>
)
}
export default About;
간단하게 Route안에 Route를 넣어주면 된다.
App.js
<div>
<ul>
<li>
<Link to="/profiles">프로필들</Link>
</li>
</ul>
<hr></hr>
<Route path="/profiles" component={Profiles}></Route>
</div>
// https://github.com/ginameee/react-playground/blob/master/router-tutorial/src/Profiles.js
<div>
<ul>
<li>
<Link to="/profiles/ginameee">ginameee</Link>
</li>
<li>
<Link to="/profiles/gildong">gildong</Link>
</li>
</ul>
<hr></hr>
<Route
path="/profiles"
exact={true}
render={() => <div>사용자를 선택해주세요</div>}
></Route>
<Route
path="/profiles/:username"
component={Profile}
>
</Route>
</div>
라우팅에 사용된 컴포넌트가 아니어도, withRouter
를 사용하면 location, match, history 등의 routing 정보에 접근이 가능하게 해준다.
// https://github.com/ginameee/react-playground/blob/master/router-tutorial/src/WithRouterSample.js
import { withRouter } from 'react-router-dom';
const WithRouterSample = ({ location, match, history }) => {
return (
<div>
<h4>location</h4>
<textarea
value={JSON.stringify(location, null, 2)}
rows={7}
readOnly
>
</textarea>
<textarea
value={JSON.stringify(match, null, 2)}
rows={7}
readOnly
>
</textarea>
<button onClick={() => history.push("/")}>
홈으로
</button>
</div>
);
}
export default withRouter(WithRouterSample);
Path에 일치하는 단 하나의 route만을 보여준다.
일치하는 정보가 없을 때의(404) 처리도 가능하다 (path를 지정하지 않을경우 기본 페이지가 된다.)
<Switch>
<Route path="/" component={Home} exact={true}></Route>
<Route path="/about" component={About}></Route>
<Route path="/profiles" component={Profiles}></Route>
<Route path="/history" component={HistorySample}></Route>
<Route
render={
({ location }) => (
<div>
<h2>이 페이지는 존재하지 않습니다.</h2>
<p>{location.pathname}</p>
</div>
)
}></Route>
</Switch>