처음 보여줄 Home 컴포넌트 생성, 웹 사이트를 소개하는 About 컴포넌트 생성
Router 컴포넌트 사용해 현재 경로에 따라 다른 컴포넌트 렌더링
// App.js
import About from './About'
import Home from './Home'
import {Route} from 'react-router-dom'
...
return (
<div>
<Route path='/' component={Home}>
<Route path='/about' component={About}>
</div>
)
이 경우 about 페이지에 HOME 컴포넌트도 함께 렌더링 된다.
<Route path='/' component={Home} exact={true}>
일반 웹 페이지 : a 태그 사용
리액트에서는 a 태그 사용하면 안된다.
Link 컴포넌트
<Link to="주소">내용</Link>
Link 설정
return (
<div>
<ul>
<li>
<Link to="/">홈</Link>
</li>
<li>
<Link to="/about">소개</Link>
</li>
</ul>
<Route path='/' component={Home}>
<Route path='/about' component={About}>
</div>
)
Route 하나에 여러 개의 path 설정
// Route 하나당 컴포넌트 설정
<Route path='/' component={Home} exact={true}>
<Route path='/about' component={About}>
<Route path='/info' component={About}>
// Route 하나에 여러 path 설정
<Route path='/' component={Home} exact={true}>
<Route path={['/about', '/info']} component={About}>
뒷부분에 유동적인 username 값을 넣어 줄 때 해당 값을 props로 받아 와서 조회하는 방법
App.js
<li>
<Link to="/profile/velopert">velopert 프로필</Link>
</li>
<li>
<Link to="/profile/dongwon">dongwon 프로필</Link>
</li>
<Route path="/profile/:username" component={Profile} />
Profile.js
const data = {
velopert: {
name: '김민준',
description: '리액트 저자',
},
dongwon: {
name: '김동원',
description: '공부 중',
},
};
const Profile = ({ match }) => {
const { username } = match.params;
const profile = data[username];
if (!profile) {
return <div> 존재하지 않는 사용자입니다.</div>;
}
return (
<div>
<h3>
{username}({profile.name})
</h3>
<p>{profile.description}</p>
</div>
);
};
location 객체
{
"pathname": "/about",
"search": "?detail=true"
"hash" : ""
}
About.js
const query = qs.parse(location.search, {
ignoreQueryPrefix: true,
});
const showDetail = query.detail === 'true';
서브 라우트: 라우트 내부에 또 라우터를 정의하는 것
Profiles.js
<ul>
<li>
<Link to="/profiles/velopert">velopert</Link>
</li>
<li>
<Link to="/profiles/dongwon">dongwon</Link>
</li>
</ul>
<Route
path="/profiles"
exact
render={() => <div>사용자를 선택해 주세요.</div>}
/>
App.js
<li>
<Link to="/profiles"> 프로필</Link>
</li>
...
<Route path="/profiles" component={Profiles} />
라우터로 사용된 컴포넌트가 아니어도 match, location, history 사용 가능
WithRouterSample.js
import { withRouter } from 'react-router-dom';
const WithRouterSample = ({ location, match, history }) => {
return (
<div>
<h4>location</h4>
<textarea
value={JSON.stringify(location, null, 2)} // 들여쓰기가 적용된 상태로 문자열 만들어줌
rows={7}
readOnly={true}
/>
<h4>match</h4>
<textarea
value={JSON.stringify(match, null, 2)}
rows={7}
readOnly={true}
/>
<button onClick={() => history.push('/')}>홈으로</button>
</div>
);
};
export default withRouter(WithRouterSample);
<Switch>
<Route path="/" component={Home} exact={true} />
<Route path={['/about', '/info']} component={About} />
<Route path="/profiles" component={Profiles} />
<Route
render={({ location }) => (
<div>
<h2>이 페이지는 존재하지 않습니다.</h2>
<p>{location.pathname}</p>
</div>
)}
/>
</Switch>
현재 경로와 Link에서 사용하는 경로가 일치하는 경우 특정 스타일, CSS 클래스를 적용할 수 있는 컴포넌트
NavLink가 활성화되어 스타일을 적용할 때는 activeStyle을, CSS 클래스를 적용할 때는 activeClassName을 props로 넣어 준다.
Profiles.js
const activeStyle = {
background: 'black',
color: 'white',
};
<li>
<NavLink activeStyle={activeStyle} to="/profiles/velopert">
velopert
</NavLink>
</li>