2021. 7. 6. 21:02ㆍBig Dreamer_Developer/React
Getting Ready for the Router
For navigation, use react-router-dom
- react-router-dom: the package to do navigation in React
npm install react-router-dom
mkdir, components & routes
in routes folder, make a file "Home.js" and "About.js". this is two router, that meand "Ok, good you go to about.js or hmode.js"
// App.js
import React from 'react';
import { HashRouter, Route } from 'react-router-dom';
import Home from './routes/Home';
import About from './routes/About';
import Detail from './routes/Detail';
import Navigation from './components/Navigation';
function App() {
return (
<>
<HashRouter>
<Navigation />
<Route path="/" exact={true} component={Home} />
<Route path="/about" component={About} />
<Route path="/movie/:id" component={Detail} />
</HashRouter>
<footer></footer>
</>
);
}
export default App;
make router in App.js here.
router을 만들고, 그 router안에는 스크린을 넣는 것이다.
Building the Router
router는 엄청 심플한 리액트 컴토넌트인데, 라우터는 url를 가져다가 확인하고 그리고 우리가 라우터에 뭘 명령했느냐에 따라 컴포넌트를 불러온다.
HashRouter 안속에 Route를 넣어주는데, Route에는 매우 중요한 props가 들어간다. 한 prop은 렌더링할 스크린이 들어가고, 다른 prop은 뭘 할지 정해주는 것이다. 예를 들어서
<Route path="/about" component={About} />
위 코드를 해석하자면, path="about" => about.js로 들어가서(path) 그리고 보여줘(component) => About(component)를 보여줘! 라는 의미이다. 결국 내가 이 path로 가면 보여줘, about이라는 component를 이라는 뜻이다.
localhost:3000/#/about
에 들어가면 우리가 입력한 내용을 컴포넌트 형태로 보여주고있다.
url를 이용해서 path를 지정해줄수 있다.
위와 같은 방식으로, index.js도 다음과 같이 설정해줄수있다.
<Route path="/" exact={true} component={Home} />
exact={true}를 추가한 것은 오로지 우리가 설정한 url 이 /일때만 home을 렌더링해주기 때문이다. 만약 /something이라면, 그건 무시한다. 결국 exact는 자신의 설정값 아니면 다른 건 렌더링 안하겠다는 뜻이다. 2개 혹은 여러개의 다른 컴포넌트를 따로 렌더링 해주는 기능을 가지고있음.
Building the Navigation
Link는 라우터 안에 있어야하며(Link는 router 밖에서 쓸 수 없다) to와 같이 쓴다
< a href="link" >< / a > doesn't work because it's an HTML thing. HTML refreshes the page every time you go somewhere
--> You don't want it on a single page application in React
=> Instead:
import { Link } from "react-router-dom";
< Link to="/" >Home< / Link >
< Link to="/" >About< / Link >
--> We change really quickly without refreshing and killing the whole page
You cannot use outside of a router
- This doesn't mean you have to put everything inside a router
You need a fragment to render both two components at the same time:
function App() {
return (
<>
< HashRouter >
< Navigation / >
< Route path="/" exact={true} component={Home} / >
< Route path="/about" component={About} / >
< / HashRouter >
< footer >< / footer >
< / >
);
}
BrowserRouter: doesn't have /#/ in the link
- a little bit annoying to set up correctly on gh-pages
'Big Dreamer_Developer > React' 카테고리의 다른 글
React Hooks_useTabs (0) | 2021.07.07 |
---|---|
React Hooks_useInput (0) | 2021.07.07 |
Rendering The Movies (0) | 2021.07.03 |
Fetching Movies from API (0) | 2021.07.03 |
Planning the Movie Component (0) | 2021.07.03 |