React Router

devyunie·2024년 8월 31일

React

목록 보기
17/20
post-thumbnail

React Router Package(Liberary)

  • react의 SPA(single page application)에서 라우팅을 구현하기 위한 라이브러리
  • 웹페이지에서 다양한 경로에 따른 뷰를 관리할 수 있도록 도와줌
  • 웹어플리케이션 내에서 URL 이동이 있을때 브라우저를 새로고침 하지 않습니다. (서버에 새로운 요청을 보내지 않습니다.)
  • 웹어플리케이션 내에서 네이비게이션 역할을 수행

Package 종류및 설치

  1. React-router
  2. React-router-dom
$ npm install react-router react-router-dom

<BrowserReouter />

  • root 경로에 있는 index.tsx의 root.render()안에 <App/> 컴포넌트를 <BrowserRouter /> 컴포넌트로 묶어야함

  • URL를 사용하여 브라우저 주소 표시줄에 현재위치를 저장하고 탐색할 수 있도록 하는 컴포넌트

root.render(
	<React.StrictMode>
		<BrowserRouter>		
			<App />
		</BrowserRouter>
	</React.StrictMode>
);

특정 URL 패턴에 대해서 컴포넌트를 각각 다르게 렌더링 하고자 한다면 App.tsx에<Routs>컴포넌트와 <Route>컴포넌트를 사용하여 경로에 따라 화면을 다르게 보이게 하는게 가능

<Routes />

  • <Route> 컴포넌트로 URL에 따른 컴포넌트들을 렌더링을 할수 있도록 도와줌

<Route />

  • URL 패턴에 따라서 렌더링 하고자 하는 컴포넌트를 지정하는 컴포넌트
  • <Route />속성
    • path 속성: URL 패턴을 지정
    • element 속성 : 렌더링할 컴포넌트 지정 (요소 자체로 지정 가능)
    • index 속성: 현재 라우터의 기본 라우터 지정

  1. Route를 통한 이동 방법
function App() {
	return (
		<Routes>
			<Route index element={<h1>기본페이지</h1>}/>
			<Route path = '/component/component' element = {<Component/>} />
			<Route path = '/component/ClassComponent' element = {<ClassComponent/>} />
			<Route path = '/component/CurlyBraces' element={<CurlyBraces/>}/>
		</Routes>
	);
}

  1. Route를 통해 공통 경로를 묶어 부모로 지정 하여 자식 경로로 이동
  • 부모에 element 지정시 자식 경로로는 진입이 불가능하다
    <Route path='/component' element = {<Component/>}>

방법

<Route path='/component'>
	<Route path = 'component' element = {<Component/>} />
	<Route path = 'ClassComponent' element = {<ClassComponent/>} />
	<Route path = 'FunctionComponent' element = {<FunctionComponent/>} />
	<Route path = 'CurlyBraces' element={<CurlyBraces/>}/>
</Route>

  1. 부모에 element를 통해 자식에 공통적으로 보여줄 (요소), (컴포넌트)를 렌더링 가능
  • <Outlet /> : 부모 <Route>에 해당 컴포넌트가 element로 등록되었을때 자식 <Route>의 element가 해당위치에 렌더링 되도록 하는 컴포넌트
  • useLocation() : 현재 경로에 대한 객체를 반환하는 react-router 훅함수
    • pathname : 현재 path 경로
function Layout(){
	const {pathname} = useLocation();
	console.log(pathname);
	
	return(
		<div>
			<div style={{height: '100px', backgroundColor:'red'}}></div>
			<Outlet/>
			<div style={{height: '100px', backgroundColor:'blue'}}></div>
		</div>
	)
}

return(
	<Route path='/component' element = {<Layour/>}>
		<Route path = 'component' element = {<Component/>} />
		<Route path = 'ClassComponent' element = {<ClassComponent/>} />
		<Route path = 'FunctionComponent' element = {<FunctionComponent/>} />
		<Route path = 'CurlyBraces' element={<CurlyBraces/>}/>
	</Route>
)

PathMove 함수에 대한 설명
1.<a />

  • a요소를 경로 이동을 하게 되면 브라우저가 새로운 요청을 보냄
  • 현재 페이지의 상태가 유지되지 않음

2.<Link>

  • 현재 웹 어플리케이션 내에서 URL을 변경할수 있도록 하는 컴포넌트
  • <Link />는 새로운 요청을 보내지 않음
  • 외부 페이지로 이동하고자 할때 <a />요소 사용해야함

‼️주의점

  • 컴포넌트 클릭 시 다른 작업을 같이 수행한다면 해당 작업이 정상적으로 완료되지 않을수 있다.
  • 특정 작업 결과에따라 다른 경로로 이동하고 싶을 때 <Link />컴포넌트를 사용할수 없음
  • 하단 코드에서 onclick을 통해 페이지는 아직 for문이 동작하는데 페이지가 이동이 되어버림

3.location 객체

  • location 객체의 href 값 변경으로 경로를 이동하면 새로운 요청을 보낸다.
  • 현재 웹 어플리케이션의 상태를 유지할수 없다.

4.useNavigate()

  • navigator 함수를 반환하는 react-router 훅 함수
  • navigator 함수 : 새로운 요청없이 path를 변경해주는 함수
export default function PathMove() {

	const onClick = () =>{
		for(let index = 0 ; index <100;index++){
			console.log(index+'실행중...');
		}

		const flag =false;
		if(!flag)return;

	}

	const onLocationHref = () => {
		window.location.href = 'http://localhost:3000/component';
	};

	const navigator = useNavigate();
	const onNavigator = () => {
		navigator('/component');
	}

	return (
		<div>
		<a href="http://localhost:3000/component">앵커</a>
		<br />
		<Link onClick={onClick} to='/component'>링크 컴포넌트</Link>
		<br />
		<button onClick={onLocationHref}>location.href</button>
		<br />
		<button onClick={onNavigator}>navigator</button>
		</div>
	)
}

PathVariable() 함수 코드
useParams()

  • 경로 변수에 해당하는 값을 읽을 때 사용하는 react-router의 훅함수
export default function PathVariable() {

	const { name } = useParams();

	return (
		<div>
			NAME: {name}
		</div>
	)
}

QueryString 함수
useSearchParam()

  • url에서 Query String 값을 받을 수 있도록 하는 react-router의 훅 함수
export default function QueryString() {
	
	const [queryParam] = useSearchParams();
	const name = queryParam.get('name');
	const age = queryParam.get('age');

	return (
		<div>
			<div style={{backgroundColor:'red'}}></div>
			NAME : {name} / AGE : {age};
		</div>
	)
}

app.tsx

<Routes>
	<Route path = '/router'>
		//http://localhost:3000/router/query-String?name=홍길동&age=23
		<Route path = 'query-String' element={<QueryString/>}/>
		
		//http://localhost:3000/router/path-Valiable/홍길동
		<Route path = 'path-Valiable/:name' element={<PathVariable/>}/>
		
		<Route path = 'path-move' element={<PathMove/>}/>
	</Route>
</Routes>

💡전체 경로에서 이동이 불가능할 경우 404Error Page 호출 방법

 <Route path='*' element={<h1>404 Error !!!</h1>}/>

0개의 댓글