라우팅(Routing) 다른 경로(url 주소)에 따라 다른 View(화면)를 보여주는 것
설치법
npm install react-router-dom --save
import {
BrowserRouter as Router,
Switch,
Route,
} from 'react-router-dom';
ⓐas ⓑ는
ⓐ를 ⓑ로 부르겠다
라는 의미
최상위를<Router></Router>
(Browser Router을)로 감싸줘야함
class Routes extends React.Component {
render() {
return (
<Router>
<Nav />
<Switch>
<Route exact path="/" component={Login} />
<Route exact path="/signup" component={Signup}/>
<Route exact path="/main" component={Main} />
</Switch>
<Footer />
</Router>
)
}
}
export default Routes;
exact path="/<Url-name>"
component={<component-name>}
👉로컬 주소 뒤에/<Url-name>
을 적으면<component-name>
컴포넌트로이동한다.- Routes.js는 index.js있는 곳에 만들어 준다.
- app.js에서 추가적인 로직을 줄께 아니면 index.js에 연결시켜주면 된다.
- Switch밖에는
<nav />
,<Footer />
넣어 모든 페이지에 동일하게 들어가는 것을 넣어준다.
a태그 vs link태그
- a 태그는 외부사이트로 이동
- link태그는 React Application 내에 페이지 전환
구분하는 이유 a 태그는 새로고침을 하고 link태그는 새로고침하지 않음
import React from 'react';
import { withRouter } from 'react-router-dom';
class Login extends React.Component {
goToMain = () => {
this.props.history.push('/main');
}
// 실제 활용 예시
// goToMain = () => {
// if(response.message === "valid user"){
// this.props.history.push('/main');
// } else {
// alert("너 우리 회원 아님. 가입 먼저 해주세요")
// this.props.history.push('/signup');
// }
// }
render() {
return (
<div>
<button
className="loginBtn"
onClick={this.goToMain}
>
로그인
</button>
</div>
)
}
}
export default withRouter(Login);
- 상단에 import { withRouter } from 'react-router-dom';
- 하단에 export default withRouter (컴포넌트 이름)
- withRouter(함수)는 인자로 Login으로 받고 기능을 추가하여 새로운 컴포넌트를 주게된다
함수를 만들 때에는 arrow function으로 만들어주는데 일반함수의 this는 동적이게 되므로 error가 날 수 있기에 확실하게 바운딩을 사용하든 아니면 arrow function으로 만들어줘야한다.
(arrow function은 this가 고정적이다.)
link태그 vs withRouterHOC
- 단순히 페이지 이동하고 싶을 때 link태그 사용
- 어떤 로직에 따라서 이동할 때 withRouterHOC를 이용
(ex: login을 했을 때 백엔드에서 user와 password가 맞았을 때 정보를 보내주고 ture값이면 페이지 이동가능하게 만들 수 있다.)
설치법
npm install node-sass --save
@import url(<scss-name.scss>)
로 받아서 사용한다.&
은 &:hover
로 써도 되고 2개 이상의 class를 가지고 있을 때 &.클래스이름
을 적어준다.