TIL 29 | React Router

dabin *.โ—Ÿ(หŠแ—จห‹)โ—ž.*ยท2021๋…„ 9์›” 2์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
4/14
post-thumbnail

๋ผ์šฐํŒ…์ด๋ž€?

url ์ฃผ์†Œ์— ๋”ฐ๋ผ ๋‹ค๋ฅธ view๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ์ด๋‹ค. ๋ฆฌ์•กํŠธ๋Š” ์ด๋Ÿฐ ๊ธฐ๋Šฅ์ด ๋‚ด์žฅ๋˜์–ด ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€์žฅ ์ธ๊ธฐ์žˆ๋Š” Third-party Library์ธ React-router๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž.

Route Component

npm ๋˜๋Š” yarn์œผ๋กœ ๋ฆฌ์•กํŠธ ๋ผ์šฐํŠธ ์„ค์น˜ ํ›„ index.js์™€ ๊ฐ™์€ ์œ„์น˜์— Routes.js ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์ค€๋‹ค.

//Route.js

import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
} from 'react-router-dom';

import Login from './pages/Login/Login';
import List from './pages/List/List';
import Detail from './pages/Detail/Detail';

class Routes extends React.Component {
  render() {
		return (
	    <Router> // or <BrouserRouter>
	      <Switch>
			<Route exact path="/" component={Login}/>
	        <Route exact path="/list" component={List} />
	        <Route exact path="/detail" component={Detail} />
	      </Switch>
	    </Router>
	  )
	}
}

export default Routes;
//index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './Routes';
import "./styles/reset.scss";

ReactDOM.render(<Routes />, document.getElementById('root'));

Route ์ด๋™ ๋ฐฉ๋ฒ•

  • DOM์—์„œ <a>๋กœ ๋ณ€ํ™˜๋œ๋‹ค. ํ•˜์ง€๋งŒ ์™ธ๋ถ€ ์‚ฌ์ดํŠธ๋กœ ์ด๋™์‹œํ‚ค๋Š” aํƒœ๊ทธ์™€ ๋‹ฌ๋ฆฌ Link๋Š” ํ”„๋กœ์ ํŠธ ๋‚ด์—์„œ ํŽ˜์ด์ง€๋ฅผ ์ „ํ™˜์‹œ์ผœ์ค€๋‹ค.
  • ํด๋ฆญ์‹œ ๋ฐ”๋กœ ์ด๋™ ๊ตฌํ˜„
//Login.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './Login.scss';

class Login extends Component {
	render() {
    	return(
        	<>
            </>
        )
   	}
}

export default Login;

withRouterHOC(higher order component) ์‚ฌ์šฉ

  • onClick ๋“ฑ ์ด๋ฒคํŠธ ์‚ฌ์šฉ
  • this.props.history(route์ •๋ณด)์— ์ ‘๊ทผํ•ด ์ด๋™
  • ์ถ”๊ฐ€ ๋กœ์ง ์žˆ์„ ๊ฒฝ์šฐ ์œ ์šฉ
import React from 'react';
import { withRouter } from 'react-router-dom';

class Login extends Component {

  goToListPage = () => {
    this.props.history.push('/list');
  }

  render() {
    return (
      <div>
        <button
          className="loginBtn"
          onClick={this.goToListPage}
        >
          ๋กœ๊ทธ์ธ
        </button>
      </div>
    )
  }
}

export default withRouter(Login); //์ฃผ์˜
profile
๋ชจ๋ฅด๋Š”๊ฒƒํˆฌ์„ฑ์ด

0๊ฐœ์˜ ๋Œ“๊ธ€