React
[React 오류 해결] react-router-dom 관련 Uncaught Error 두개의 오류
py0922
2024. 5. 6. 00:38
1. 오류
A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>
오류 원인 : react-router-dom 버전 6 이상부터는 <Route>를 <Routes>로 감싸줘야한다고 한다.
오류가 발생한 코드
import {BrowserRouter, Route} from 'react-router-dom'
....
function App(){
return (
...
<Route path="/"><Home></Home></Route>
<Route path="/topics"><Topics></Topics></Route>
<Route path="/contact"><Contact></Contact></Route>
...
)
}
오류 해결
: <Routes> 추가
import {BrowserRouter, Route, Routes} from 'react-router-dom'
....
function App(){
return (
...
<Routes>
<Route path="/"><Home></Home></Route>
<Route path="/topics"><Topics></Topics></Route>
<Route path="/contact"><Contact></Contact></Route>
</Routes>
...
)
}
2. 오류
두 번째 오류가 발생함.
Uncaught Error: [Home] 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 사용한다.
음... 그러니까 Route 태그안에는 component가 있으면 안된다. component를 element로 변경해준다.
아까 첫 번째 오류 해결한 코드가 두 번째 오류 발생 코드이다.
오류 해결
: element 사용
import {BrowserRouter, Route, Routes} from 'react-router-dom'
....
function App(){
return (
...
<Routes>
<Route path="/" elemenet={<Home />}></Route>
<Route path="/topics" elemenet={<Topics />}></Route>
<Route path="/contact" elemenet={<Contact />}></Route>
</Routes>
...
)
}
끝-
반응형
LIST