[React 에러 일지] ... is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

🚫 [...] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

react-router-dom v6부터는,

  • Switch 대신 Routes를 사용
  • Route 안에 component 대신 element 사용

그리고 <Routes> 자식으로는 <Route>만 가능하다. 따라서 v6 이전처럼 아래와 같이 코드를 작성하면 에러가 발생하는 것이다.

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/">
            <LandingPage />
          </Route>
          <Route path="/login">
            <LoginPage />
          </Route>
          <Route path="/register">
            <RegisterPage />
          </Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

<Routes> 자식으로는 <Route>만 가능한데 <LandingPage />, <LoginPage />, <RegisterPage />가 존재하기 때문에 에러가 발생한 것이다.


아래와 같이 수정해주면 된다.

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={ <LandingPage /> } />
          <Route path="/login" element={ <LoginPage /> } />
          <Route path="/register" element={ <RegisterPage /> } />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

좋은 웹페이지 즐겨찾기