Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Upcoming SlideShare
What to Upload to SlideShare
What to Upload to SlideShare
Loading in …3
×
1 of 23

11.react router dom

0

Share

Download to read offline

react router

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all

11.react router dom

  1. 1. react-router-dom 임광규 2020.ReactJS 1
  2. 2. SPA SPA는SinglePageApplication의약어입니다.말그대로한개의페이지로구성된애플리케 이션을뜻합니다. 전총적인웹페이지는여러페이지로구성되어있습니다. 2020.ReactJS 2
  3. 3. 라우팅 다른주소에다른화면을보여주는것을 라우팅 이라고합니다. 리액트라이브러리자체에이기능이내장되어있지는않습니다. 리액트라우팅라이브러리는리액트라우터(react-router),리치라우터(reach-router),Next.js등 여러가지가있습니다. 이중가장오랫동안사용되었고사용빈도역시높은 리액트 라우터 를알아봅니다. 2020.ReactJS 3
  4. 4. SPA의단점 SPA의단점은앱의규모가커지면자바스크립트파일이너무커진다는것입니다. 페이지로딩시사용자가실제로방문하지않을수도있는페이지의스크립트도불러오기때문입 니다. 이때코드스플리팅(codesplitting)을사용하면라우트별로파일을나누어서트래픽과로딩속도를 개선할수있습니다. 2020.ReactJS 4
  5. 5. 리액트라우터설치 설치는아래명령어를이용해서진해합니다. $ yarn add react-router-dom or $ npm install react-router-dom --save 2020.ReactJS 5
  6. 6. 라우터적용 index.js import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; ReactDOM.render(<BrowserRouter> <App /> </BroserRouter>, document.getElementById('root')); } 2020.ReactJS 6
  7. 7. 라우터적용 app.js import React from 'react'; import { Route } from 'react-router-dom'; import About from './About'; import Home from './Home'; export default () => { return ( <div> <Route path="/" component={Home} exact={true} /> <Route path="/about" component={About} /> </div> ); } 2020.ReactJS 7
  8. 8. Router 사용법 Route컴포넌트를사용하여사용자의현재경로에따라다른컴포넌트를보여줄수있습니다. <Route path="주소규칙" component={보여 줄 컴포넌트} /> 2020.ReactJS 8
  9. 9. Link 컴포넌트를사용하여다른주소로이동 Link컴포넌트는클릭하면다른주소로이동시켜주는컴포넌트입니다. 일반웹에서는a태그를사용하여페이지를전환하는데리액트라우터를사용할때는이태그를 직접사용하면안됩니다. 사용법 <Link to="주소">내용</Link> 2020.ReactJS 9
  10. 10. Link컴포넌트사용예 app.js import React from 'react'; import { Route, Link } from 'react-router-dom'; import About from './About'; import Home from './Home'; export default () => { return ( <div> <ul> <li><Link to="/">홈</Link></li> <li><Link to="/about">소개</Link></li> </ul> <Route path="/" component={Home} exact={true} /> <Route path="/about" component={About} /> </div> ); } 2020.ReactJS 10
  11. 11. Route하나에여러개의path설정하기 Route하나에여러개의path를지정하는것은최신버전의리액트라우터v5부터적용된기능 입니다. /about , /info 에접근시About컴포넌트로보여줌 import React from 'react'; import { Route } from 'react-router-dom'; import About from './About'; import Home from './Home'; export default () => { return ( <div> <Route path="/" component={Home} exact={true} /> <Route path={['/about', '/info']} component={About} /> </div> ); } 2020.ReactJS 11
  12. 12. URL파라미터와쿼리 페이지주소를정의할때가끔은유동적인값을전달해야할때도있습니다. 이를파라미터와쿼리로나눌수있습니다. 파라미터예시:/info/lahuman 쿼리예시:/about?id=lahuman 2020.ReactJS 12
  13. 13. URL파라미터예 /info페이지에서파라미터를사용시/info/:id형식으로값을넣어주어props로받아와서조회 가가능합니다. import React from 'react'; export default ({ match }) => { const { id } = match.params; return ( <div> <h1> {id} </h1> </div> ); } 2020.ReactJS 13
  14. 14. app.js import React from 'react'; import { Route, Link } from 'react-router-dom'; import About from './About'; import Info from './Info'; import Home from './Home'; export default () => { return ( <div> <ul> <li><Link to="/">홈</Link></li> <li><Link to="/about">소개</Link></li> <li><Link to="/info/lahuman">lahuman 정보 조회</Link></li> </ul> <Route path="/" component={Home} exact={true} /> <Route path="/about" component={About} /> <Route path="/info/:id" component={Info} /> </div> ); } 2020.ReactJS 14
  15. 15. URL쿼리 쿼리는location객체에들어있는search값에서조회할수있습니다. location객체는라우트로사용된컴포넌트에게props로전달되며웹의현재주소에대한정보 를지니고있습니다. location객체정보 { "pathname": "/about", "search": "?id=lahuman", "hash": "" } 2020.ReactJS 15
  16. 16. qs라이브러리 쿼리문자열로객체로변환할때는qs라이브러리를사용하여쉽게처리할수있습니다. $ yarn add qs or $ npm install qs --save 2020.ReactJS 16
  17. 17. URL쿼리예제 qs를이용하여파싱된결과는언제나문자열입니다. import React from 'react'; import qs from 'qs'; export default ({location}) => { const query = qs.parse(location.search, { ignoreQueryPrefix: true // 문자열 맨 앞의 ?를 생략 합니다. }); return <h1>{query.id}</h1> } 2020.ReactJS 17
  18. 18. 서브라우트 서브라우트는라우트내부에도라우트를정의하는것을의미합니다. 그냥라우트로사용되고있는컴포넌트의내부에Route컴포넌트를또사용하면됩니다. import React from 'react'; import { Route, Link } from 'react-router-dom'; import Info from './Info'; export default () => { return ( <div> <ul> <li><Link to="/info/abcd">abcd 정보 조회</Link></li> <li><Link to="/info/lahuman">lahuman 정보 조회</Link></li> </ul> <Route path="/info" exact render={() => <div>사용자를 선택해주셔요.</div>} /> <Route path="/info/:id" component={Info} /> </div> ); } 2020.ReactJS 18
  19. 19. 리액트라우터부가기능 .history 라우트로사용된컴포넌트에match,location과함께전달되는props중하나로,이객체 를통해컴포넌트내에구현하는메소드에서구현하는메서드에서라우터API를호출할수 있습니다. .withRouter HoC(Higher-orderComponent)로라우트로사용된컴포넌트가아니어도match, location,history객체를접근할수있게해줍니다. .Switch 여러Route를감싸서그중일치하는단하나의라우트만랜더링시켜줍니다.모든규칙과 일치하지않을때NotFound페이지도구현할수있습니다. .NavLink Link와비슷,단링크가활성화되었을때의스타일을activeStyle에적용하면됩니다. 2020.ReactJS 19
  20. 20. history예제 import React from 'react'; export default ({history}) => { return ( <div> <button onClick={() => history.push('/')}>홈으로</button> <button onClick={() => history.goBack()}>뒤로</button> </div> ); } 2020.ReactJS 20
  21. 21. withRouter예제 import React from 'react'; import { withRouter } from 'react-router-dom'; export default withRouter(({location, match, history}) => { const query = qs.parse(location.search, { ignoreQueryPrefix: true // 문자열 맨 앞의 ?를 생략 합니다. }); return <div> <h1>{query.id}</h1> <button onClick={() => history.push('/')}>홈으로</button> <button onClick={() => history.goBack()}>뒤로</button> </div> }) 2020.ReactJS 21
  22. 22. Switch예제 import React from 'react'; import { Route, Link, Switch } from 'react-router-dom'; import About from './About'; import Info from './Info'; import Home from './Home'; export default () => { return ( <div> <ul> <li><Link to="/">홈</Link></li> <li><Link to="/about">소개</Link></li> <li><Link to="/info/lahuman">lahuman 정보 조회</Link></li> </ul> <Switch> <Route path="/" component={Home} exact={true} /> <Route path="/about" component={About} /> <Route path="/info/:id" component={Info} /> <Route render={({location}) => <div> <h2>페이지가 존재 하지 않습니다.</h2> <p>{location.pathname}</p> </div>} /> </Switch> </div> ); } 2020.ReactJS 22
  23. 23. NavLink예제 import React from 'react'; import { Route, NavLink } from 'react-router-dom'; import Info from './Info'; export default () => { const activeStyle = { background: 'red', color: 'white' } return ( <div> <ul> <li><NavLink activeStyle={activeStyle} to="/info/abcd" active>abcd 정보 조회</NavLink></li> <li><NavLink activeStyle={activeStyle} to="/info/lahuman">lahuman 정보 조회</NavLink></li> </ul> <Route path="/info" exact render={() => <div>사용자를 선택해주셔요.</div>} /> <Route path="/info/:id" component={Info} /> </div> ); } 2020.ReactJS 23

×