바스키아
Router) 서브 라우트 만들기 본문
Sub Route 라우트 안에 라우트 만들기!!
라우트를 통해 컴포넌트를 열었는데 그안에 또 라우트를 이용해야해 이럴때....사용(사실 내가 당장 필요한부분이였음)
import * as React from 'react';
import Profile from './Profile';
import {Route, Link} from 'react-router-dom';
function Profiles() {
return (
<div>
<h3>사용자목록</h3>
<ul>
<li><Link to="/profiles/beom">beom</Link></li>
<li><Link to="/profiles/homer">homer</Link></li>
</ul>
<Route path="/profiles" exact render={( match, loaction ) => <div>사용자를 선택해주세요</div>} />
<Route path="/profiles/:username" component={Profile} />
</div>
);
}
export default Profiles;
|
exact 이그젝트 쓰는이유는 전글에 설명되어있고..
유의할점은 이부분이다.
<Route path="/profiles" exact render={( match, loaction ) => <div>사용자를 선택해주세요</div>} />
path로 라우트를 이동했을때 render ={ 하고 바로 렌더할 dom요소드를 넣어줄수 있다.
전시간에 이용한 match, location 을 이용해서 바로 요소를 넣을수도 있는점!
Link to 로 beom or homer 에따라 :username이 분별해서 component={Profile} 컴포넌트를 불러올것이다.
(쉽지? 근데 이거 몰라서 해메고 있었다....)
내블로그는 인기 블로그가 아니기에 전에 작성하였던 Profile.js파일을 보여줄께
import * as React from 'react';
const profileData = {
beom :{
name : 'beom',
description : "Front Engine ...MyInfo ...etc"
},
homer : {
name : '호머 심슨',
description : '심슨가족 아빠 주인공'
}
}
/**
* message를 입력받아 출력하는 함수입니다.
* @param match{string} 출력할 메세지 입니다.
*/
function Profile({ match }) {
const { username } = match.params;
const profile = profileData[username];
if(!profile){
return <div>존재하지 않는 사용자입니다. </div>
}
return (
<div>
<h3>{username} ({profile.name})</h3>
<p>
{profile.description}
</p>
</div>
);
}
export default Profile;
|
이제 준비는 끝났다.
app.js 에서
<Route path="/profiles" component={Profiles} />
라우트만 추가해주면 끝이다.
쉬운거 인정이냐.... 인정이냐!!!???!?!!?!!
결과 감상하시죠
프로필 목록 들어가보자 (Profiles.js)
homer을 누르면
<li><Link to="/profiles/homer">homer</Link></li>
이부분 Link타고 들어가겠지 이부분은 바로
<Route path="/profiles/:username" component={Profile} />
:username 은 homer가 될것이다
결과
끝 쉽고 빠르고 간결했다.
'JS > React' 카테고리의 다른 글
리액트 시작하기 (0) | 2019.08.31 |
---|---|
Router) Router의 부가기능 (.feat history, withRouter) (0) | 2019.08.30 |
Router) 파라미터와 쿼리 (0) | 2019.08.30 |
Router) 사용하기 (0) | 2019.08.29 |
Router) What is..... React - Router (0) | 2019.08.26 |