[React] React Router

김성현·2021년 8월 1일
0

React

목록 보기
1/2

react-router-dom

  • 리액트 SPA 구현에 사용
  • 기존 방식의 a태그를 사용하면 모든 페이지가 reload 하여 로드 시간이 오래걸린다.
  • 새로고침 대신 Router를 사용하면 변경된 소스만 바꿈으로 속도가 빠르다.
  • BrowserRouter, HashRouter, Route, Link

설치

npm i react-router-dom

High Level Router : BrowserRouter, HashRouter, MemoryRouter, NativeRouter

BrowserRouter

브라우저 history API를 사용하여 새로고침 없이 주소 변경 가능

  • 현재 주소에 관련된 정보 props로 전달
    • history,location,match
  • 동적인 페이지에 적합
  • 새로고침시 경로를 찾지 못해 에러 발생 -> 서버 세팅 필요

HashRouter

URL의 hash를 활용한 라우터

  • 정적인 페이지에 적합
  • 주소에 해쉬(#) 붙음
  • 새로고침시 에러 안남
  • SEO불리 -> 관리자페이지나 SEO에 상관없는 페이지에 사용

HashRouter은 URL 해시를 서버에서 읽을 수 없기 때문에 SSR로 설정을 백업할 수 없다. 또한 History location을 지원하지 않기에 BrowserRouter를 사용하는 것을 선호한다.

Route

브라우저에서 요청한 경로와 같거나 포함하는 경우 해당 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 />} 
/>

Switch

여러 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>

라우터 구조

withRouter

Higher-order Component로 컴포넌트를 감싸서 사용
Route로 사용되지 않은 컴포넌트도 match, location, history객체 접근 허용

const Sample = ({match, location, history}) =>{
  return <div></div>
}

export default withRouter(Sample);

History API

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>
        )
    }
}

Router Hooks

useHistory: withRouter없이 history 사용

const history = useHistory();

useParams: path parameter 바로 사용

const parms = useParams();

참고자료
리액트 분석하기

profile
JS개발자

0개의 댓글