본문 바로가기

Programing/react

[React] - react-router-dom

npm install react-router-dom@6

npm 설치

 

세팅
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
      <BrowserRouter>
        <App />
      </BrowserRouter>
  </React.StrictMode>
);

<BrowserRouter> app 감싸기

 

페이지 나누는 법
import { Routes, Route, Link } from 'react-router-dom'
import Detail from './routes/Detail.js'
import About from './roues/About.js'

function App(){
  return (
    ...
    <Routes>
      <Route path="/detail" element={ <Detail/> } />
      <Route path="/about" element={ <About/> } />
    </Routes>
  )
}

 

페이지 이동 버튼
<Link to="/">홈</Link>
<Link to="/detail">상세페이지</Link>

 

페이지 이동기능 useNavigate()
const App = () =>{
  let navigate = useNavigate()
  
  return (
    (생략)
    <button onClick={()=>{ navigate('/detail') }}>이동버튼</button>
  )
}

navigate(2) 숫자넣으면 앞으로가기, 뒤로가기 기능개발도 가능합니다.

-1 넣으면 뒤로 1번 가기

2 넣으면 앞으로 2번 가기 기능입니다. 

 

404 page
<Route path="*" element={ <div>404 not found</div> } />

<Route path="*"> 하나 맨 밑에 만들어두면 됩니다.

* 경로는 모든 경로를 뜻해서

위에 만들어둔 /detail 이런게 아닌 이상한 페이지 접속시 * 경로로 안내해줍니다. 

 

서브경로 만들 수 있는 nested routes
<Route path="/about" element={ <About/> } >  
  <Route path="member" element={ <div>멤버들</div> } />
  <Route path="location" element={ <div>회사위치</div> } />
</Route>

<Route>안에 <Route>를 넣을 수 있는데 이걸 Nested routes 라고 부릅니다.

저렇게 쓰면

/about/member로 접속시 <About> &<div>멤버들</div> 을 보여줍니다.

/about/location으로 접속시 <About> & <div>회사위치</div> 을 보여줍니다.

 

동적페이지 생성
<Route path="/detail/:id" element={ <Detail computer={computer}/> }/>

페이지를 여러개 만들고 싶으면 URL 파라미터라는 문법을 사용가능합니다.

path 작명할 때 /:어쩌구 이렇게 사용하면 "아무 문자"를 뜻합니다.

'Programing > react' 카테고리의 다른 글

[React] - Lifecycle, useEffect  (0) 2023.04.22
[React] - styled-components  (0) 2023.04.22
[React] - 이미지 넣는 법  (0) 2023.04.21
[React] - input 태그  (0) 2023.04.21
[React] - state 값 전달 props  (0) 2023.04.21