🐾 [react] router 사용하는 방법

react-router-dom 사용 환경 준비
- yarn에서 react-router-dom를 설치
yarn add react-router-dom
- App.js에 코드를 작성했다.
class App extends Component {
render() {
return (
<HashRouter>
<Switch>
<Route path={'/'} component={Main}/>
</Switch>
<Switch>
<Route path={'/study'} component={Study}/>
</Switch>
</HashRouter>
);
}
}
- Switch: 자식컴포넌트로 생성된 Route 중에 첫번째 Route를 렌더링 해준다. 이걸 통하여 특정 컴포넌트만 렌더링해서 화면을 띄울 수 있다.
- Route : 특정 컴포넌트마다 URL 지정해준다
- Main.js
import {useHistory} from "react-router-dom";
const Main = () => {
const history = useHistory();
return (
<>
<div>
<Button onClick={() => {
history.push("/study")
}}>공부하기</Button>
</div>
</>
);
}
- 메인에 있는 공부하기 버튼을 누르면 http://localhost:3000/study로 이동하면서 study 페이지가 로딩된다.