Notice
Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

0strich

[React Router] useParams 본문

Front End/React Router

[React Router] useParams

0strich 2020. 4. 16. 13:49

react-router-dom의 useParams hook을 사용해서 하나의 컴포넌트에서 전달받은 URL Parameter를 사용해서 적용시켜 보자

 

다음은 useParams를 사용하는 예제이다.

 

App.js

import React from "react";
import {
  BrowserRouter,
  Switch,
  Route,
  Redirect,
  useHistory,
  useParams,
} from "react-router-dom";

// App 컴포넌트
const App = () => {
  return (
    <BrowserRouter>
      <h1>Resume</h1>
      {/* Buttons 컴포넌트 */}
      <Buttons />
      <br></br>
      {/* 라우팅 */}
      <Switch>
        <Route exact path="/:path" component={Path} />
        <Route path="/" render={() => <Redirect to="about" />} />
      </Switch>
    </BrowserRouter>
  );
};

// useHistory 를 사용하는 Buttons 컴포넌트
const Buttons = () => {
  const history = useHistory();
  const button = (path) => (
    <button onClick={() => history.push(`/${path}`)}>{path}</button>
  );
  return (
    <div>
      {button("about")}
      {button("skillls")}
      {button("projects")}
    </div>
  );
};

// useParams 를 사용하는 Path 컴포넌트
const Path = () => {
  const { path } = useParams();
  return <div>This page's url is {path}</div>;
};

export default App;

 

작동되는 화면은 다음과 같다.

 

하나의 컴포넌트에서 URL Parameter를 활용해 변환되는 것을 확인할 수 있다.

'Front End > React Router' 카테고리의 다른 글

[React Router] useHistory  (0) 2020.04.15
[React Router] react-router-dom  (0) 2020.04.15
Comments