공부 기록/React

[React] Router을 사용해서 URL parameter에 따라 화면 다르게 보이기

뵤옹 2023. 7. 3. 17:59

React를 공부하면서 페이지를 만들고 있다보니 효율적이지 못한 페이지여도 새롭게 하나하나 React의 기능들을 알아가고 있다.

이전까지는 React에서 JSP와 같이 URL에 정보를 담는 법을 알지 못해 session 영역에 데이터를 저장한다든가, 변화하는 값을 target해서 target 된 값에 따라 백엔드 서버로 값을 넘기는 주소를 달리한다든가의 일을 여러 번 처리하게 만들었었다. 하지만 중복되는 코드가 늘어나면서 비효율적인 코드가 될 수밖에 없었다.

 

이번엔 Router을 사용하면서 URL에 담겨있는 parameter를 추출하고, parameter에 따라 페이지가 다르게 보이도록 만든 것을 정리하려 한다.

 

1. URL에 parameter 포함하기

URL에 parameter를 붙이는 여러 방법에 대한 자세한 포스팅은 아래의 포스팅을 참고하였다.

https://gongbu-ing.tistory.com/44

 

React | Router : URL로 parameter 전송하기

이전 포스팅에서 SPA의 한계를 극복하고자 라우터를 이용하여 경로에 알맞은 컴포넌트를 불러오는 방법에 대해 공부했다. React | Router : URL로 페이지 접근하기 Single Page Application(SPA) SPA는 서버로

gongbu-ing.tistory.com

기본 주소에서 실시간 위치 이력 페이지로 넘어갈 때 URL을 /myPage/currentLocation?site=(선택한 parameter)로 지정하려고 한다.

index.js

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <>
    <React.StrictMode>
      <BrowserRouter>
        <Routes>
          <Route exact path='/' element={<Navigate to="/myPage" replace />} />
          <Route exact path='/myPage' element={<Map><App /></Map>} />
          <Route path='/myPage'>
            <Route exact path='currentLocation' element={<MapCurrent><CurrentLocation /></MapCurrent>} />
          </Route>
        </Routes>
      </BrowserRouter>
    </React.StrictMode>

SearchPage.js

import { useState } from 'react';

function SearchPage({onDataChange}} {
	
    const [site, setSite] = useState("1");
    // 기타 생략
    
    const toCurrentLocation = `/myPage/currentLocation?site=${site}`;
    
    return(
    	<>
        // 생략
        <Link to={toCurrentLocation}>
        	<Button variant='outlined' color='warning' size='small'>실시간 조회</Button>
        </Link>
        </>
    )
}

기본 Router에서는 컴포넌트의 기본 URL을 작성하고 이동시킬 버튼을 클릭할 때는 query 주소를 사용하여 기본 URL 뒤에 parameter가 붙어 이동하도록 하였다.

이렇게 페이지를 넘어갈 수 있고 target된 값이 다르면 동일한 페이지에 URL이 site=2로 뜬다.

그렇다면 URL로 넘어온 parameter를 읽고 그에 따라 화면은 다르게 보여보자.

 

2. URL에서 parameter 값 읽어오기

CurrentLocation.js

import { useState } from 'react';

function CurrentLocation() {
	const [site, setSite] = useState();
    const [siteLocation, setSiteLocation] = useState("A");
    
    useEffect(() => {
    	const params = new URLSearchParams(window.location.search);
        setSiteSeq(params.get("site"));
        
        if(params.get("site") === 1) {
        	setSiteLocation("A");
        } else if(params.get("site") === 2) {
        	setSiteLocation("B");
        } else {
        	setSiteLocation("x");
        }
        
        axios.get('/currentLocation', { params: {site: params.get("site")} })
        .then(res => {
        	console.log(res);
        })
        .catch(error => {
        	console.log(error);
        })
    }, []);
    
    return(
    	<h2>이력: {siteLocation}</h2>
    )
    
}

자세한 내용은 모두 생략하였지만 중요한 코드는 위와 같이 작성하면 된다.

페이지가 로드될 때 window.location을 console로 찍으면 search 값을 확인할 수 있다.

저 search 값에 따라 페이지를 다르게 보이도록 하고 싶으므로 URLSearchParam을 사용해서 URL에 들어있는 search 요소를 parameter로 저장하여 로직 처리를 한다.

 


[ 참고 ]

https://gongbu-ing.tistory.com/44

https://znznzn.tistory.com/64

https://velog.io/@wiostz98kr/TIL51-l-React-Router-3탄