본문 바로가기

React

react-router-dom (3) URL 파라미터와 쿼리

페이지 주소를 정의할 때, 

가끔 유동적인 값을 전달해야 할 때도 있다.

파라미터와 쿼리 두가지로 나눌 수 있다.

 

 

파라미터 예시

:/profiles/yumcoding

 

쿼리 예시

:/about?icecream=true

 

 

유동적인 값을 사용해야 하는 상황에서 파라미터를 사용해야 할지 쿼리를 사용해야 할지 모르겠을 때?

정해진 규칙은 없다!

다만 일반적으로!

파라미터 -> 특정 아이디 혹은 이름을 사용해서 조회할 때

쿼리 -> 키워드 검색, 페이지에 필요한 옵션 전달할 때

 

 

 

 

  • URL 파라미터

 

/propfile/yumcoding, profile/webearbears와 같은 형식으로

뒷부분에 유동적인 username 값을 넣어줄 때,

해당 값을 props로 받아 와서 페이지에 띄우는 방법

 

 

우선, Profile 컴포넌트를 만든다.

import React from "react";

const data = {
  yumcoding: {
    name: "yumyum",
    description: "a developer who loves to play with React",
  },
  myfav: {
    name: "serang",
    description: "my favourite novelist",
  },
};

const Profile = ({ match }) => {
  const { username } = match.params;

  const profile = data[username];

  if (!profile) {
    return <div>Not found</div>;
  }

  return (
    <div>
      <h3>
        {username}({profile.name})
      </h3>
      <p>{profile.description}</p>
    </div>
  );
};

export default Profile;

 

URL 파라미터를 사용 할 때는

라우트로 사용되는 컴포넌트에서 받아오는 

match라는 객체 안의 params 값을 참조.

(match 객체 안에는 현재 컴포넌트가 어떤 경로 규칙에 의해 보이는지에 대한 정보가 들어있다.)

 

 

 

 

 

 

이제 App 컴포넌트에서 Profile 컴포넌트를 위한 라우트를 정의해 본다.

import React from "react";
import { Route, Link } from "react-router-dom";
import Home from "./component/Home";
import About from "./component/About";
import Profile from "./component/Profile";

import "./App.css";

const App = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to="/">HOME</Link>
        </li>
        <li>
          <Link to="/about">ABOUT</Link>
        </li>
        <li>
          <Link to="/profile/yumcoding">yumcoding profile</Link>
        </li>
        <li>
          <Link to="/profile/myfav">myfav profile</Link>
        </li>
      </ul>
      <hr />
      <Route path="/" component={Home} exact={true} />
      <Route path={["/about", "/info"]} component={About} />
      <Route path="/profile/:username" component={Profile} />
    </div>
  );
};
export default App;

 

 

path에 /profile/:username이라고 넣어 준다.

이렇게 설정하면 match.params.username 값을 통해 

현재 username 값을 조회할 수 있다.

 

 

 

 

 

 

 

 

 

 

 

 

  • URL 쿼리

 

쿼리는 loacation 객체에 들어 있는 search 값에서 조회할 수 있다.

location 객체는 라우트로 사용된 컴포넌트에게 props로 전달되며, 

웹 애플리케이션의 현재 주소에 대한 정보를 지니고 있다.

 

location의 형태

{
	"pathname": "/about",
	"search":"?detail=true",
	"hash":""
}

 

 

위 객체는

https://localhost:3000/about?detail=true

주소로 들어갔을 때의 값이다.

 

 

 

 

URL 쿼리를 읽을 때는 위 객체가 지닌 값 중에서 search 값을 확인해야 한다. (문자열 형태)

 

이때, URL 쿼리는

?detail=true&another=1

과 같이 문자열에 여러 값 설정 가능하다.

 

 

 

 

 

 

search 값에서 특정 값을 읽어 오기 위해서는 이 문자열을 객체 형태로 변환해야 한다.

쿼리 문자열을 객체로 변환할 떄는 qs라는 라이브러리를 사용한다.

 

$ npm add qs

 

 

//About.js


import React from "react";
import qs from "qs";

const About = ({ location }) => {
  const query = qs.parse(location.search, {
    ignoreQueryPrefix: true, //이 설정을 통해 문자열 맨 앞의 ?를 생략
  });
  console.log(query);
  const showDetail = query.detail === "true"; //쿼리의 파싱 결과 값은 문자열

  return (
    <div>
      <h1>About</h1>
      <p>This project is to practice react-router</p>
      {showDetail && <p>hey, can you see me now?</p>}
    </div>
  );
};

export default About;

 

 

쿼리 문자열을 객체로 파싱하는 과정에서

결과 값은 항상 문자열이다!!!!!

?value=1 혹은 ?value=true 처럼 숫자나 boolean을 사용한다고 해도

해당 값이 우리가 원하는 형태롤 변환되는 것 아님!

"1"이나 "true"와 같이 문자열 형태라는 것 잊지 말기!!!

 

그래서 만약 숫자를 받아 와야 하면?

parseInt 함수 사용

 

boolean 값을 사용해야 하면?

정확히 "true" "false"와 일치하는지 비교