설치
npm i react-router-dom
High Level Router :
BrowserRouter
,HashRouter
,MemoryRouter
,NativeRouter
브라우저 history API
를 사용하여 새로고침 없이 주소 변경 가능
history
,location
,match
URL의 hash를 활용한 라우터
HashRouter은 URL 해시를 서버에서 읽을 수 없기 때문에 SSR로 설정을 백업할 수 없다. 또한 History location을 지원하지 않기에 BrowserRouter를 사용하는 것을 선호한다.
브라우저에서 요청한 경로와 같거나 포함하는 경우 해당 component 렌더링
<Route path="/url" component={렌더링할 컴포넌트} />
exact
: 정확한 url 사용, /
경로에는 관용적으로 사용Dynamic 라우팅
path parameter
/profile/1
resource 식별에 사용<Route path="/profile/:id" component={Profile} />
컴포넌트에서 다음과 같은 방식으로 값 사용(문자열 값)
const id = props.match.params.id
query parameter
/profile?name=kim
정렬이나 필터링에 사용
컴포넌트에서 사용하기
URLSearchParams
(IE 지원 x)const searchParams = props.location.search const obj = new URLSearchParams(searchParams) obj.get('name') // get메소드로만 값에 접근 가능
query-string
라이브러리(권장)import queryString from 'query-string'; const searchParams = props.location.search const query = queryString(searchParams) query.name // 객체처럼 사용 가능
Redirect
해당 url로 Redirect<Route path="/login" render={()=> isLogin ? <Redirect to="/" /> : <Login />} />
여러 Route 중 먼저 맞는 하나만 렌더링
exact
를 사용하지 않는 로직
Not Found
페이지 적용
<BrowserRouter>
<Switch> // 범위가 좁은 순서대로 배치
<Route path="/profile/:id" component={Profile} />
<Route path="/profile" component={Profile} />
<Route path="/" exact component={Home} />
<Route component={NotFound} /> // 404
</Switch>
</BrowserRouter>
현재 페이지에서 상태를 유지하면서 History API
를 사용하여 주소만 변경
<Link to='이동할주소'>내용</Link>
a
태그로 변환(+ 페이지 전환 방지)NavLink
active 상태
: 현재 경로와 Link에서 사용하는 경로가 일치하는 경우
- active 상태에 대한 스타일 또는 CSS 클래스 지정 가능
activeStyle
: 스타일activeClassName
: 클래스exact
사용 가능- 주로 네비게이션에 사용
<NavLink to="url" activeStyle={activeStyle} activeClassName={activeClassName} isActive={(match, location) => { return 활성화할 조건 }}> About </NavLink>
Higher-order Component
로 컴포넌트를 감싸서 사용
Route
로 사용되지 않은 컴포넌트도 match, location, history
객체 접근 허용
const Sample = ({match, location, history}) =>{
return <div></div>
}
export default withRouter(Sample);
history.goBack()
: 뒤로 가기
history.push('url')
: url로 이동
브라우저 히스토리 API
DOM의 Window 객체는 history 객체를 통해 브라우저의 세션 기록에 접근할 수 있는 방법을 제공
- pushstate(state, title, url)
- replacestate(state, title, url)
- popstate()
export class App extends Component { componentDidMount() { window.onpopstate = function (e) { this.console.log( `location: ${document.location}, state: ${e.state}` ) } } render() { return ( <div> <button onClick={() => window.history.pushState('v1', '', '/page1')} > page1 </button> <button onClick={() => window.history.pushState('v2', '', '/page2')} > page2 </button> </div> ) } }
useHistory: withRouter없이 history 사용
const history = useHistory();
useParams: path parameter 바로 사용
const parms = useParams();
참고자료
리액트 분석하기