Router 라이브러리
2021. 10. 22. 16:15ㆍReact/문법
- react-router-dom 라이브러리 적용(<a href="..." /> 사용 금지, 사용하려면 e.preventDefault()와 자바스크립트 주소로 수동 변경 필요)
// * App 을 BrowserRouter 로 감싸기
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
1. Route : 특정 주소에 컴포넌트 연결하기
<Route path="주소규칙" component={보여주고싶은 컴포넌트} exact={boolean값}>
- path : 연결시킬 주소 ex> path="/"
- component
- exact : path가 정확히 일치할 때만 Route 시킬지 결정하는 prop
2. Link : 누르면 다른 주소 연결하기(a 태그와는 다르게 HTML5 History API 를 사용하여 브라우저의 주소만 바꿀뿐 페이지를 새로 불러오지는 않습니다.)
const App = () => {
return (
<div>
<ul>
<li>
<Link to="/">홈</Link>
</li>
<li>
<Link to="/about">소개</Link>
</li>
</ul>
<hr />
<Route path="/" exact={true} component={Home} />
<Route path="/about" component={About} />
</div>
);
};
3. Switch : 여러 Route 들을 감싸서 그 중 규칙이 일치하는 라우트 단 하나만을 렌더링(아무것도 일치하지 않았을때 보여줄 Not Found 페이지를 구현 할 수도 있습니다.)
const App = () => {
return (
<div>
...
<hr />
<Switch>
<Route path="/" exact={true} component={Home} />
<Route path="/about" component={About} />
<Route path="/profiles" component={Profiles} />
<Route path="/history" component={HistorySample} />
<Route
// path 를 따로 정의하지 않으면 모든 상황에 렌더링됨
render={({ location }) => (
<div>
<h2>이 페이지는 존재하지 않습니다:</h2>
<p>{location.pathname}</p>
</div>
)}
/>
</Switch>
</div>
);
};
4. Redirect : history.replace 처럼 작동
import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard"/>
) : (
<PublicHomePage/>
)
)}/>
'React > 문법' 카테고리의 다른 글
SPA(Single Page Application) (0) | 2021.10.22 |
---|---|
라우터 컴포넌트 props (0) | 2021.10.22 |
API 연동 - Context 사용 (0) | 2021.10.22 |
API 연동 - 커스텀 Hook or 라이브러리 이용 (0) | 2021.10.22 |
API 연동 (0) | 2021.10.22 |