SPA (Single Page Application)

  • 서버에서 주는 html이 1개만 있는 어플리케이션
  • 전통적인 웹사이트 : 페이지를 이동할 때마다 정적자원들(html, css, js)을 내려줌
  • SPA : 딱 한번만 정적자원을 받아옴

라우팅

  • 브라우저 주소에 따라 다른 페이지를 보여주는 것
  • SPA에서 html은 딱 하나만 있지만 브라우저 주소창대로 다른 페이지를 보여줄 수 있음

리액트에서 라우팅 처리하기

  • react-route-dom 패키지 설치하기
yarn add react-router-dom

적용하기

1. index.js에 BrowserRouter 적용하기

import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';

ReactDOM.render(
	<BrowserRouter>
		<App />
	</BrowserRouter>
	document.getElementById("root")
);
  • BrowserRouter : 웹 브라우저가 가지고 있는 주소 정보를 props로 넘겨줌

 

2. 세부 화면 만들기

  • Home.js
const Home = (props) => {
	return (
		<div>메인 화면</div>
	)
}

export default Home;
  • Cat.js
const Cat = (props) => {
	return (
		<div>고양이</div>
	)
}

export default Cat;
  • Dog.js
const Dog = (props) => {
	return (
		<div>강아지</div>
	)
}

export default Dog;

 

3. App.js에서 Route 적용하기

  • Route 사용 방법 1) 넘겨줄 props가 없을 때
<Route path="주소[ex. /home]" component={[보여줄 컴포넌트]}/>
  • Route 사용 방법 2) 넘겨줄 props가 있을 때
<Route path="주소" render={(props) => (<BucketList list={this.state.list}/>)} />
  • App.js에 적용하기
import {Route} from 'react-router-dom';

class App extends React.Component {
	constructor(props){
		super(props);
		this.state={};
	}

	render(){
		return (
			<div className="App">
				<Route path="/" exact component={Home}/>
				<Route path="/cat" component={Cat}/>
				<Route path="/dog" component={Dog}/>
			</div>
		);
	}
}

export default App;
  • "/"가 "/cat"와 "/dog"에 포함되어 있기 때문에 exact 추가

4. URL 파라미터 사용하기

  • 파라미터 : /cat/nabi
  • 쿼리 : /cat?name=nabi
  • App.js
<Route path="/cat/:cat_name" component={Cat}/>
  • Cat.js에서 console.log(props.match); 콘솔로 파라미터 확인 가능

5. 링크 이동시키기

1) <Link/> 사용하기

<Link to="주소">[텍스트]</Link>
  • App.js
import {Route, Link} from 'react-router-dom';

class App extends React.Component {
	constructor(props){
		super(props);
		this.state={};
	}

	render(){
		return (
			<div className="App">
				<div>
					<Link to="/">Home으로 가기</Link>
					<Link to="/cat">Cat으로 가기</Link>
					<Link to="/dog">Dog으로 가기</Link>
				</div>

				<hr/>
				<Route path="/" exact component={Home}/>
				<Route path="/cat" component={Cat}/>
				<Route path="/dog" component={Dog}/>
			</div>
		);
	}
}

export default App;

2) history 사용하기

  • App.js
import {withRouter} from 'react-router';
import {Route, Link} from 'react-router-dom';

class App extends React.Component {
	constructor(props){
		super(props);
		this.state={};
	}

	componentDidMount(){
		console.log(this.props);
	}

	render() {
		return (
			<div className="App">
				<div>
					<Link to="/">Home으로 가기</Link>
					<Link to="/cat">Cat으로 가기</Link>
					<Link to="/dog">Dog으로 가기</Link>
				</div>
	
				<hr/>
				<Route path="/" exact component={Home}/>
				<Route path="/cat" component={Cat}/>
				<Route path="/dog" component={Dog}/>
	
				<button onClick={() => {
					this.props.history.push("/cat");
				}}>
					cat으로 가기
				</button>
				<button onClick={() => {
					this.props.history.goBack();
				}}>뒤로가기</button>
			</div>
		);
	}
}
//내보내는 부분에서 withRouter로 감싸주기
export default withRouter(App);
  • push([이동할 주소]) : 페이지 이동시킴
  • goBack() : 뒤로가기

 

잘못된 주소 처리하기 (Switch 이용)

  • NotFound.js
const NotFound = (props) => {
	return <h1>주소가 올바르지 않습니다</h1>;
);

export default NotFound;
  • App.js
render() {
	return (
		<div className="App">
			...
			<Switch>
				<Route
					path="/"
					exact
					render={(props) => {
						<BucketList
							list={this.state.list}
							history={this.props.history}
						/>
					}}
				/>
				<Route path="/detail" component={Detail}/>
				<Route component={NotFound}/>
			</Switch>
			...
		</div>
	);
}
  • NotFound 컴포넌트를 주소 없이 연결함
  • Switch는 첫번째로 매칭되는 path를 가진 컴포넌트를 렌더링함

+ Recent posts