본문 바로가기
개발/React

[react] react-router-dom 버전 6에서 변경된 사항 (ft. 'Switch' is not exported from 'react-router-dom' 오류)

by 코딩하는 갓디노 2021. 12. 21.

[react] react-router-dom 버전 6에서변경된 사항

 

react-router-dom 6에서
변경된 사항입니다.  

 

react-router-dom이 버전 6으로 바뀌면서 몇가지가 바뀌었습니다.

  • switch -> routes 
  • component -> element
  • useHistory -> useNavigate

 

route, switch

before: react-router-dom이 버전 5

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Header from "./components/Header/Header";
import MovieDetail from "./components/MovieDetail/MovieDetail";
import PageNotFound from "./components/PageNotFound/PageNotFound";

function App() {
  return (
    <div className="app">
      <Router>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/movie/:imdbID" component={MovieDetail} />
          <Route component={PageNotFound} />
        </Switch>
      </Router>
    </div>
  );
}

export default App;

 

after: react-router-dom이 버전 6

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./screens/mobile/pages/Home";
import MovieDetail from "./components/MovieDetail/MovieDetail";
import PageNotFound from "./screens/admin/pages/PageNotFound";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="/movie/:imdbID" element={<MovieDetail />} /> //상대경로로 변경
        <Route element={<PageNotFound />} />
      </Routes>
    </BrowserRouter >
  );
}

export default App;

 

useHistory

  • 명칭 useHistory에서 useNavigate으로 변경되었습니다.
  • useHistory의 기능 중 { go, goBack, goForward }는 각각 해당 위치로, 뒤로, 다음으로의 기능인데, 이 부분도 navigate로 통일하고 index를 넣는것으로 변경되었습니다.
  • 뒤로가기 history.goBack() -> naviagate(-1)

before: react-router-dom이 버전 5

import { useHistory } from "react-router-dom";

function App() {
  const history = useHistory()
  const onClickHandle = () => {
	    history.push("/home");
  }
  
  const goBack = () => { //뒤로가기 
        history.goBack()
        window.scrollTo(0, 0);
  }
  
  return (
    <div>
      <button onClick={onClickHandle}>home</button>
    </div>
  );
}

 

after: react-router-dom이 버전 6

import { useNavigate } from "react-router-dom";

function App() {
  const navigate = useNavigate();
  const onClickHandle () => {
    navigate("/home");
  }
  
  const goBack = () => { //뒤로가기 
        navigate(-1)
        window.scrollTo(0, 0);
  }
  
  return (
    <div>
      <button onClick={onClickHandle}>home</button>
    </div>
  );
}

 

404 에러 페이지 경우

<Route path="*" element={<NotFound />} />

 

자세한 내용은 아래의 공식 문서를 참고하시면 됩니다. 

https://reactrouter.com/docs/en/v6/upgrading/v5

 

React Router | Upgrading from v5

Declarative routing for React apps at any scale

reactrouter.com

 

반응형

댓글