라우트 내부에 또 라우트를 정의하는 것
import {Link,Route} from 'react-router-dom'
import Profile from './Profile'
const Profiles = () =>{
return (
<div>
<h3>사용자 목록</h3>
<ul><Link to="/profiles/heyhey">현홍</Link></ul>
<ul><Link to="/profiles/gildong">길동</Link></ul>
<Route path="/profiles" exact
render={()=><div>사용자를 선택해 주세요</div>}/>
<Route path="/profiles/:username" component={Profile}/>
</div>
)
}
export default Profiles
<Route path="/profiles" exact render={()=><div>사용자를 선택해 주세요</div>}/>
render
라는 props를 넣어주었다.exact
만 적어도 알아서 exact ={true}
라고 설정된다.profile 지우고 profiles로 연결
<li><Link to='/profiles'>프로필</Link></li>
<Route path="/profiles" component={Profiles}/>
profiles 로 가는 Route를 만들고
<Route path="/profiles" component={Profiles}/>
Route 와 연결되는 Link도 만들어 준다
<li><Link to='/profiles'>프로필</Link></li>
Profiles.js 에서
/profiles
뿐이라면: <Route path="/profiles" exact render={()=><div>사용자를 선택해 주세요</div>}/>
Route와 같지만 component로 이동되는 것이 아닌 render()
을 통해 보여주기만 한다./profiles/이름
이 들어온다면 <Route path="/profiles/:username" component={Profile}/>
Profile component
로 이동한다Profile.js 에서
:username
의 위치를 찾는다match.params
에 있다정말 떠나실 건가요?
import React,{Component} from 'react'
class HistorySample extends Component{
handleGoback = ()=>{
this.props.history.goBack()
}
handleGoHome = ()=>{
this.props.history.push('/')
}
componentDidMount(){
this.unblock = this.props.history.block('정말 떠나시나요')
}
componentWillUnmount(){
if (this.unblock){
this.unblock()
}
}
render(){
return(
<div>
<button onClick={this.handleGoback}>뒤로</button>
<button onClick={this.handleGoHome}>홈</button>
</div>
)
}
}
export default HistorySample
handleGoback = ()=>{this.props.history.goBack()}
뒤로가기
handleGoHome = ()=>{this.props.history.push('/')}
' / '(홈)으로 가기
componentDidMount(){this.unblock = this.props.history.block('정말 떠나시나요') }
이것을 설정하고 나면 페이지ㅣ에 변화가 생길려고 할때 나갈 건지 질문한다.
componentWillUnmount(){ if (this.unblock){this.unblock()}}
컴포넌트가 언마운트되면 질문을 멈춘다.
라우트로 사용된 컴포넌트가 아니어도 match, location, history 객체를 접근할 수 있게 한다.
여러 route를 감싸서 그중 일치하는 단 하나의 라우트만을 렌더링 시켜준다.
모든 규칙과 일치하지 않을 때 보여줄 Not Found페이지도 구현 가능하다
import { Route,Link,Switch} from 'react-router-dom';
<Switch>
<Route path="/" component={Home} exact={true}/>
<Route path="/about" component={About}/>
<Route path="/profiles" component={Profiles}/>
<Route path="/history" component={HistorySample}/>
<Route render={({location})=>(
<div>
<h2>이 페이지는 존재 안합니다.</h2>
<p>{location.pathname}</p>
</div>
)} />
</Switch>
Link와 사용방법 비슷
현재 경로와 Link에서 사용하는 경로가 일치하는 경우 특정 스타일 적용가능
import {NavLink,Route} from 'react-router-dom'
const Profiles=()=>{
const activeStyle ={
background:'white',
color:'black'
}
<ul><NavLink activeStyle={activeStyle} to="/profiles/heyhey">현홍</NavLink></ul>
<ul><NavLink activeStyle={activeStyle} to="/profiles/gildong">길동</NavLink></ul>
}