본문 바로가기
Frontend/React

react router v6 변경 사항

by Forsaken Developer 2023. 2. 21.
728x90
728x90

react router v6 변경 사항

Switch → Routes

<Switch>
  <Route path="/products">
    <Products />
  </Route>

  <Route path="/products/:productId">
    <ProductDetail />
  </Route>
</Switch>
<Routes>
  <Route path="/products">
    <Products />
  </Route>

  <Route path="/products/:productId">
    <ProductDetail />
  </Route>
</Routes>

element

<Route path="/products">
  <Products />
</Route>
<Route path="/products" element={<Products />} />

시작 경로 일치

<Route path="/products/*" element={<Products />} />

최적의 경로를 찾음(순서 상관 없음)

<Route path="/products/:productId" element={<ProductDetail />} />
<Route path="/products/edit" element={<ProductEdit />} />

NavLink activeClassName

<NavLink activeClassName={classes.active} to="/abount">
  Abount
</NavLink>
<NavLink className={(navData)=>navData.active ? classes.active : '' } to="/abount">
  Abount
</NavLink>

Redirect → Navigate

<Route path="/" exact>
  <Redirect to="/home"/>
</Route>
<Route path="/" element={<Navigate replace to="/home" />} />

중첩 라우팅 사용 시 Routes로 감싸고 상대경로 사용

<Route path="/about/*" element={<About />} />
<Routes>
  <Route path="me" element={<p>About me</p>} />
</Routes>

자식 요소로 중첩 라우팅 사용

<Route path="/about/*" element={<About />} >
  <Route path="me" element={<p>About me</p>} />
</Route>

Outlet으로 라우팅 위치 설정

const About = ()=> {
  return(
    <section>
      <h1>About page<h1>
      <Outlet />
    </section>
  )
}

useNavigate()

const history = useHistory();
history.replace("/");
const navigate = useNavigate();
navigate("/", {replace : true});
728x90
반응형

댓글