카테고리 없음

[ReactJS] Route 최신 v6 (Switch 안씀)

mswait 2022. 3. 16. 23:03

https://mswait.tistory.com/127

 

[ReactJS] [Movie App] [3] - Router & Link, ReactJS의 위력(Switch 포함)

* Swith 가 Route 로 대체 되기 전의 내용이다. 업데이트 된 내용은 하단 참조 import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; 라우터에는 두가지 종류가 있다. 1. Hash Router 2...

mswait.tistory.com

의 최신 v6 (switch 안씀)


 

https://reactrouter.com/docs/en/v6/getting-started/overview
from v6, they don't use switch
--------------------------------------------------------------------------
Upgrade all "Switch" elements to "Routes"
React Router v6 introduces a Routes component that is kind of like Switch, but a lot more powerful. The main advantages of Routes over Switch are:

All "Route"s and "Link"s inside a "Routes" are relative. This leads to leaner and more predictable code in "Route path" and "Link to"
Routes are chosen based on the best match instead of being traversed in order. This avoids bugs due to unreachable routes because they were defined later in your "Switch"
Routes may be nested in one place instead of being spread out in different components. In small to medium sized apps, this lets you easily see all your routes at once. In large apps, you can still nest routes in bundles that you load dynamically via React.lazy
In order to use v6, you'll need to convert all your "Switch" elements to "Routes". If you already made the upgrade to v5.1, you're halfway there.

First, let's talk about relative routes and links in v6.

 


react-router-dom 5버전 -> 버전6 바뀐 부분

1. Switch컴포넌트가 Routes컴포넌트로 대체되었습니다.
Switch -> Routes

2. Route컴포넌트 사이에 자식 컴포넌트를 넣지 않고, element prop에 자식 컴포넌트를 할당하도록 바뀌었습니다.
Route path="/" element={< Home / >}

react-router-dom 6버전 문서
https://reactrouter.com/docs/en/v6/getting-started/overview

 


1) 더이상 Switch는 쓰이지 않는다(버젼 6이상). 이제 그역할은 Routes가 대신할 것이다 (공식문서 참조), 또한 Route 태그의 exact 속성도 더이상 쓰이지 않으며 Routes가 알아서 최적의 경로배정을 해주기 때문에 Switch를 썼을 때의 고민을 말끔히 해결해 준다
2) BROWSER ROUTER가 일반적인 방식이며, HASHROUTER는 잘 쓰이진 않는다(뒤에 #이런게 붙음)
3) 한 라우트에서 다른 라우트로 가고 싶을 땐 a태그의 href을 속성이 가장 먼저 생각이 날 것이고, 실제로도 그렇게 코드를 작성하면 이동이 가능하다. 하지만 페이지 전체가 새로고침되기 때문에 리액트의 장점을 깎아먹는다. 따라서 재실행되는 것을 막기 위해 react-router-dom에서 import한 link 태그를 사용하면 된다

 

 

* 최신

아래와 같이 하면 된다. Switch는 더 이상 사용되지 않는다.

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./routes/Home";

function App() {
return <Router>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</Router>;
}

export default App;