Router-중첩라우팅
부모
<Route path="/posts" component={Postlist} />
<Route exact={true} path={`${props.match.url}`} render={() =>
<h3>Postlist</h3>} />
<Route path={`${props.match.url}/:postId`} component={Post} />
const Postlist= (props: RouteComponentProps<{}>) =>{
return(
<div>
<Route exact={true} path={`${props.match.url}`} render={() => <h3>Postlist</h3>} />
<Route path={`${props.match.url}/:postId`} component={Post} /> /** Post 호출**/
</div>
);
};
const Post= (props: RouteComponentProps<{ postId: string}>) =>{
function goNextPost() {
const nextPostId= +props.match.params.postId+ 1;
props.history.push(`/posts/${nextPostId}`);
}
return(
<div>
<h3>Post {props.match.params.postId}</h3>
<button onClick={goNextPost}>페이지 이동</button>
<p>{new URLSearchParams(props.location.search).get('body')}</p>
</div>
);
};
switch 모듈
<Switch>
<Route />
<Route />
</Switch>
일반switch 문처럼비교
<Route>의path는switch의break 같은형태=> 순서에유의해야함
switch로404 페이지띄우기
const NotFound= () =>{
return(
<h3>Not Found</h3>
);
};
<Switch>
<Route exact={true} path="/" component={Home} />
<Route path="/intro"render={() => <h3>소개</h3>} />
<Route path="/posts" component={Postlist} />
<Route component={NotFound}/>// 여기가path가안맞을경우404로띄우게함
</Switch>
Redirect
기본적으로 replace 방식(history에 남지 않는다)
constAdmin= () =>{
constisAdmin= true;
returnisAdmin
?<h3>Admin</h3>: <Redirect to="/"/>;
};
<Route path="/admin" component={Admin} />
/admin path로 접속시 isAdmin이 true일 때만 아니면 리다이렉션
oldpath
<Route path="/intro"render={() => <h3>소개</h3>} />
<Redirect from="/about" to="/intro"/>
/intro의 예전 path가 /about 였을시 /intro로리다이렉트 시켜주는 방법!!! Switch 안에서만가능
NavLink
`to`에 지정한 path와 URL이 매칭 되는 경우,
특별한 스타일, 클래스를 적용 할 수 있는Link